От новичка до гуру: Курсы программирования на CyberDuff

Вызов onCreateDialog() из диалогового окна

Я создал один SherlockDialogFragment из SherlockFragmentActivity..

Вот что я сделал до сих пор ::

DatePickerFragment newFragment = DatePickerFragment.newInstance(ReportDisplayActivity.this);
newFragment.show(getSupportFragmentManager(), "dialog");

Фрагмент диалогового окна Шерлока

public class DatePickerFragment extends SherlockDialogFragment implements android.view.View.OnClickListener
{

    private Button btnOk;
    private TextView txtFromDate;
    private TextView txtToDate;
    private int setFromYear;
    private int setFromMonth;
    private int setFromDay;
    private int setToYear;
    private int setToMonth;
    private int setToDay;

    private final static int DIALOG_FROM_DATE_PICKER = 0;
    private final static int DIALOG_TO_DATE_PICKER = 1;
    private static Context context;

    public DatePickerFragment() {
    }

    public static DatePickerFragment newInstance(Context ctx) {
        DatePickerFragment frag = new DatePickerFragment();
        Bundle args = new Bundle();
        //args.putInt("title", title);
        frag.setArguments(args);
        context=ctx;
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        View  rootView = inflater.inflate(R.layout.temp, container, false);
        txtFromDate=(TextView)rootView.findViewById(R.id.dialog_fromDate);
        txtToDate=(TextView)rootView.findViewById(R.id.dialog_toDate);
        btnOk=(Button)rootView.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(this);
        txtFromDate.setOnClickListener(this);
        txtToDate.setOnClickListener(this);

        Calendar today = Calendar.getInstance();
        setFromYear = today.get(Calendar.YEAR);
        setFromMonth = today.get(Calendar.MONDAY);
        setFromDay = today.get(Calendar.DAY_OF_MONTH);

        setToYear = today.get(Calendar.YEAR);
        setToMonth = today.get(Calendar.MONDAY);
        setToDay = today.get(Calendar.DAY_OF_MONTH);

        return rootView;
    }

    //@Override
    protected Dialog onCreateDialog(int id)
    {
        switch(id)
        {
        case DIALOG_FROM_DATE_PICKER:
            return new DatePickerDialog(context, mDateFromSetListener, setFromYear, setFromMonth, setFromDay);

        case DIALOG_TO_DATE_PICKER:
            return new DatePickerDialog(context, mDateToSetListener, setToYear, setToMonth, setToDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mDateFromSetListener = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int month, int day) {
            setFromYear = year;
            setFromMonth = month;
            setFromDay = day;
            //returnDate();
            txtFromDate.setText(setFromDay+("-")+setFromMonth+("-")+setFromYear);
        }
    };

    private DatePickerDialog.OnDateSetListener mDateToSetListener = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int month, int day) {
            setToYear = year;
            setToMonth = month;
            setToDay = day;
            txtFromDate.setText(setToDay+("-")+setToMonth+("-")+setToYear);
            //returnDate();
        }
    };
    public void onClick(View v) 
    {
        switch (v.getId()) {
        case R.id.btn_ok:
            Toast.makeText(context,"Button ok",Toast.LENGTH_SHORT).show();
            break;

        case R.id.dialog_fromDate :
            Toast.makeText(context,"From Date",Toast.LENGTH_SHORT).show();
            ((Activity) context).showDialog(DIALOG_FROM_DATE_PICKER); 
            break;
        case R.id.dialog_toDate :
            Toast.makeText(context,"To Date",Toast.LENGTH_SHORT).show();
            ((Activity) context).showDialog(DIALOG_TO_DATE_PICKER); 
            break;
        default:
            break;
        }

    }
}

Я не могу открыть диалоговое окно Datepicker из SherlockDialogFragment. Я не могу найти, что не так в моей реализации.

Если я использую активность вместо SherlockDialogFragment, тогда все работает нормально.

ИЗМЕНИТЬ ::

public class DatePickerFragment extends DialogFragment implements android.view.View.OnClickListener
{

    private Button btnOk;
    private TextView txtFromDate;
    private TextView txtToDate;
    private int setFromYear;
    private int setFromMonth;
    private int setFromDay;
    private int setToYear;
    private int setToMonth;
    private int setToDay;

    private final static int DIALOG_FROM_DATE_PICKER = 0;
    private final static int DIALOG_TO_DATE_PICKER = 1;
    private static Context context;

    public DatePickerFragment() {
    }

    public static DatePickerFragment newInstance(Context ctx) {
        DatePickerFragment frag = new DatePickerFragment();
        Bundle args = new Bundle();
        //args.putInt("title", title);
        frag.setArguments(args);
        context=ctx;
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        View  rootView = inflater.inflate(R.layout.temp, container, false);
        txtFromDate=(TextView)rootView.findViewById(R.id.dialog_fromDate);
        txtToDate=(TextView)rootView.findViewById(R.id.dialog_toDate);
        btnOk=(Button)rootView.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(this);
        txtFromDate.setOnClickListener(this);
        txtToDate.setOnClickListener(this);

        Calendar today = Calendar.getInstance();
        setFromYear = today.get(Calendar.YEAR);
        setFromMonth = today.get(Calendar.MONDAY);
        setFromDay = today.get(Calendar.DAY_OF_MONTH);

        setToYear = today.get(Calendar.YEAR);
        setToMonth = today.get(Calendar.MONDAY);
        setToDay = today.get(Calendar.DAY_OF_MONTH);

        return rootView;
    }

    //@Override
    protected Dialog onCreateDialog(int id)
    {
        switch(id)
        {
        case DIALOG_FROM_DATE_PICKER:
            return new DatePickerDialog(context, mDateFromSetListener, setFromYear, setFromMonth, setFromDay);

        case DIALOG_TO_DATE_PICKER:
            return new DatePickerDialog(context, mDateToSetListener, setToYear, setToMonth, setToDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mDateFromSetListener = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int month, int day) {
            setFromYear = year;
            setFromMonth = month;
            setFromDay = day;
            //returnDate();
            txtFromDate.setText(setFromDay+("-")+setFromMonth+("-")+setFromYear);
        }
    };

    private DatePickerDialog.OnDateSetListener mDateToSetListener = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int month, int day) {
            setToYear = year;
            setToMonth = month;
            setToDay = day;
            txtFromDate.setText(setToDay+("-")+setToMonth+("-")+setToYear);
            //returnDate();
        }
    };
    public void onClick(View v) 
    {
        switch (v.getId()) {
        case R.id.btn_ok:
            Toast.makeText(context,"Button ok",Toast.LENGTH_SHORT).show();
            break;

        case R.id.dialog_fromDate :
            Toast.makeText(context,"From Date",Toast.LENGTH_SHORT).show();
            ((Activity) context).showDialog(DIALOG_FROM_DATE_PICKER); 
            showDatePickerDialog(txtFromDate);
            break;
        case R.id.dialog_toDate :
            Toast.makeText(context,"To Date",Toast.LENGTH_SHORT).show();
            ((Activity) context).showDialog(DIALOG_TO_DATE_PICKER); 
            break;
        default:
            break;
        }
    }

    public void showDatePickerDialog(View v) 
    {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }
}

Логкэт ::

01-02 15:37:55.013: E/AndroidRuntime(933): FATAL EXCEPTION: main
01-02 15:37:55.013: E/AndroidRuntime(933): java.lang.NoClassDefFoundError: com.example.myapp.home.DatePickerFragment
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.example.myapp.report.ReportDisplayActivity$2.onItemSelected(ReportDisplayActivity.java:275)
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.actionbarsherlock.internal.widget.IcsAdapterView.fireOnSelected(IcsAdapterView.java:861)
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.actionbarsherlock.internal.widget.IcsAdapterView.access$2(IcsAdapterView.java:854)
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.actionbarsherlock.internal.widget.IcsAdapterView$SelectionNotifier.run(IcsAdapterView.java:827)
01-02 15:37:55.013: E/AndroidRuntime(933):  at android.os.Handler.handleCallback(Handler.java:587)
01-02 15:37:55.013: E/AndroidRuntime(933):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-02 15:37:55.013: E/AndroidRuntime(933):  at android.os.Looper.loop(Looper.java:130)
01-02 15:37:55.013: E/AndroidRuntime(933):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-02 15:37:55.013: E/AndroidRuntime(933):  at java.lang.reflect.Method.invokeNative(Native Method)
01-02 15:37:55.013: E/AndroidRuntime(933):  at java.lang.reflect.Method.invoke(Method.java:507)
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-02 15:37:55.013: E/AndroidRuntime(933):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-02 15:37:55.013: E/AndroidRuntime(933):  at dalvik.system.NativeStart.main(Native Method)

ИЗМЕНИТЬ 2 ::

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp"
    android:versionCode="3"
    android:versionName="3.0.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name=".MyApplication"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/Custom_ThemeSherlockLight" >
        <activity
            android:name=".SplashActivity"
            android:clearTaskOnLaunch="true"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/Custom_ThemeSherlockLight" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/Custom_ThemeSherlockLight"
            android:windowSoftInputMode="stateHidden" >
        </activity>

        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.Sherlock.Light"
            android:windowSoftInputMode="stateHidden" />

        <!-- Reports -->

        <activity
            android:name=".report.ReportDisplayActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden" >
        </activity>

        <activity
            android:name=".home.DateSelector"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden" >
        </activity>
    </application>

</manifest>

temp.xml (файл макета)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/popup_top_up"
    android:orientation="vertical"
    android:paddingBottom="5dp" >

    <TextView
        android:id="@+id/lbl_fromDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="45dp"
        android:text="From Date :"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/dialog_fromDate"
        style="@style/DropDownNav.Custom_ThemeSherlockLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/lbl_fromDate"
        android:hint="@string/lbl_select_from_date"
        android:layout_alignBottom="@+id/lbl_fromDate"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/lbl_fromDate"
        android:text="@string/lbl_select_from_date"
        android:textColor="#000000"
        android:textSize="12sp"/>

    <TextView
        android:id="@+id/lbl_toDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/lbl_fromDate"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/lbl_fromDate"
        android:layout_marginTop="22dp"
        android:text="To Date :"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/dialog_toDate"
        style="@style/DropDownNav.Custom_ThemeSherlockLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/lbl_toDate"
        android:layout_alignBottom="@+id/lbl_toDate"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/lbl_toDate"
        android:text="@string/lbl_select_to_date"
        android:textColor="#000000"
        android:textSize="12sp"/>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="81dip"
        android:layout_height="35dp"
        android:layout_below="@+id/dialog_toDate"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:background="@drawable/button_selector"
        android:text="OK"
        android:textColor="@color/white" />

</RelativeLayout>

Я могу открыть диалоговое окно, подобное этому, но когда я нажимаю на текст «выбрать из даты» или «выбрать дату» (откуда я хочу показать диалоговое окно выбора даты), диалоговое окно выбора даты не отображается.

введите здесь описание изображения

стили.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="Custom_ThemeSherlockLight" parent="@style/Theme.Sherlock.Light">
        <item name="actionBarItemBackground">@drawable/selectable_background_exampthemesherlocklightle</item>
        <item name="popupMenuStyle">@style/PopupMenu.Custom_ThemeSherlockLight</item>
        <item name="dropDownListViewStyle">@style/DropDownListView.Custom_ThemeSherlockLight</item>
        <item name="actionBarTabStyle">@style/ActionBarTabStyle.Custom_ThemeSherlockLight</item>
        <item name="actionDropDownStyle">@style/DropDownNav.Custom_ThemeSherlockLight</item>
        <item name="actionBarStyle">@style/ActionBar.Solid.Custom_ThemeSherlockLight</item>
        <item name="actionModeBackground">@drawable/cab_background_top_exampthemesherlocklightle</item>
        <item name="actionModeSplitBackground">@drawable/cab_background_bottom_exampthemesherlocklightle</item>
        <item name="actionModeCloseButtonStyle">@style/ActionButton.CloseMode.Custom_ThemeSherlockLight</item>
    </style>

    <style name="ActionBar.Solid.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ActionBar.Solid">
        <item name="background">@drawable/ab_solid_exampthemesherlocklightle</item>
        <item name="backgroundStacked">@drawable/ab_stacked_solid_exampthemesherlocklightle</item>
        <item name="backgroundSplit">@drawable/ab_bottom_solid_exampthemesherlocklightle</item>
        <item name="progressBarStyle">@style/ProgressBar.Custom_ThemeSherlockLight</item>
    </style>

    <style name="ActionBar.Transparent.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ActionBar">
        <item name="background">@drawable/ab_transparent_exampthemesherlocklightle</item>
        <item name="progressBarStyle">@style/ProgressBar.Custom_ThemeSherlockLight</item>
    </style>

    <style name="PopupMenu.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_exampthemesherlocklightle</item>
    </style>

    <style name="DropDownListView.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ListView.DropDown">
        <item name="android:listSelector">@drawable/selectable_background_exampthemesherlocklightle</item>
    </style>

    <style name="ActionBarTabStyle.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ActionBar.TabView">
        <item name="android:background">@drawable/tab_indicator_ab_exampthemesherlocklightle</item>
    </style>

    <style name="DropDownNav.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.Spinner.DropDown.ActionBar">
        <item name="android:dropDownSelector">@drawable/selectable_background_exampthemesherlocklightle</item>
    </style>

    <style name="ProgressBar.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ProgressBar.Horizontal">
        <item name="android:progressDrawable">@drawable/progress_horizontal_exampthemesherlocklightle</item>
    </style>

    <style name="ActionButton.CloseMode.Custom_ThemeSherlockLight" parent="@style/Widget.Sherlock.Light.ActionButton.CloseMode">
        <item name="android:background">@drawable/btn_cab_done_exampthemesherlocklightle</item>
    </style>

    <!-- this style is only referenced in a Light.DarkActionBar based theme -->
    <style name="Theme.Custom_ThemeSherlockLight.Widget" parent="@style/Theme.Sherlock">
        <item name="popupMenuStyle">@style/PopupMenu.Custom_ThemeSherlockLight</item>
        <item name="dropDownListViewStyle">@style/DropDownListView.Custom_ThemeSherlockLight</item>
    </style>

    <style name="Theme.Sherlock.Translucent" parent="@style/Theme.Sherlock">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:backgroundDimEnabled">false</item>
        <item name="android:backgroundDimEnabled">true</item>
    </style>

</resources>

  • Используйте DialogFragment 02.01.2014
  • Он показывает тосты? 02.01.2014
  • @Raghunandan Я использую библиотеку SherlockActionBar, поэтому мне приходится использовать SherlockDialogFragment, иначе SherlockDialogFragment и DialogFragment конфликтуют с точки зрения оператора импорта. 02.01.2014
  • @Vigbyor да, он успешно отображает тост, но не показывает DatePickerDialog. 02.01.2014
  • то же самое произойдет, если я использую только Dialog (который я использовал ранее) вместо SherlockDialogFragment. 02.01.2014
  • @AndroidLearner, привет, есть успехи? 03.01.2014
  • @Vigbyor нет, дорогая.проблема остается как есть... 03.01.2014
  • Хм, ладно, извините за вчерашний день, у меня появились новые задачи, поэтому мне пришлось уйти. Я попробую ваш код на выходных и сообщу вам позже. 03.01.2014
  • @Vigbyor без проблем, я понимаю, спасибо за проявленный интерес... :) 03.01.2014
  • Ваш styles.xml содержит только вышеуказанный код? Я считаю, что в вашем файле также определены другие индивидуальные стили, пожалуйста, поделитесь полным styles.xml файлом. 03.01.2014
  • Добавлены изменения @Vigbyor. Пожалуйста, проверьте это 03.01.2014
  • @AndroidLearner, хорошо, спасибо за обновление. 03.01.2014
  • @AndroidLearner, привет, мой ответ сработал для тебя? 07.01.2014

Ответы:


1

Вот решение,

Основная деятельность

public class MainActivity extends SherlockFragmentActivity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        DatePickerFragment newFragment = DatePickerFragment.newInstance(this);
        newFragment.show(ft, "dialog");
    }
}

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

DatePickerFragment

public class DatePickerFragment extends SherlockDialogFragment implements android.view.View.OnClickListener
{
    private final static int DIALOG_FROM_DATE_PICKER = 0;
    private final static int DIALOG_TO_DATE_PICKER = 1;
    private static Context context;
    private Button btnOk;
    private TextView txtFromDate;
    private TextView txtToDate;
    private int setFromYear;
    private int setFromMonth;
    private int setFromDay;
    private int setToYear;
    private int setToMonth;
    private int setToDay;
    private int dialog=0;

    public static DatePickerFragment newInstance( Context ctx ) 
    {
        DatePickerFragment frag = new DatePickerFragment();
        Bundle args = new Bundle();
        frag.setArguments(args);
        context=ctx;
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        View  rootView = inflater.inflate(R.layout.fragment_dialog, container, false);
        txtFromDate=(TextView)rootView.findViewById(R.id.dialog_fromDate);
        txtToDate=(TextView)rootView.findViewById(R.id.dialog_toDate);
        btnOk=(Button)rootView.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(this);
        txtFromDate.setOnClickListener(this);
        txtToDate.setOnClickListener(this);

        Calendar today = Calendar.getInstance();
        setFromYear = today.get(Calendar.YEAR);
        setFromMonth = today.get(Calendar.MONTH);
        setFromDay = today.get(Calendar.DAY_OF_MONTH);

        setToYear = today.get(Calendar.YEAR);
        setToMonth = today.get(Calendar.MONTH);
        setToDay = today.get(Calendar.DAY_OF_MONTH);

        return rootView;
    }

    private void showDatePickerDialog ( int id )
    {
        switch ( id )
        {
            case DIALOG_FROM_DATE_PICKER:
                new DatePickerDialog(context, mDateSetListener, setFromYear, setFromMonth, setFromDay).show();
                break;
            case DIALOG_TO_DATE_PICKER:
                new DatePickerDialog(context, mDateSetListener, setToYear, setToMonth, setToDay).show();
        }
    }

    @Override
    public void onClick( View v ) 
    {
        switch (v.getId()) 
        {
            case R.id.btn_ok:
                Toast.makeText(context,"Button ok",Toast.LENGTH_SHORT).show();
                break;
            case R.id.dialog_fromDate :
                dialog = DIALOG_FROM_DATE_PICKER;
                showDatePickerDialog (DIALOG_FROM_DATE_PICKER);
                break;
            case R.id.dialog_toDate :
                dialog = DIALOG_TO_DATE_PICKER;
                showDatePickerDialog(DIALOG_TO_DATE_PICKER);
                break;
            default:
                break;
        }           
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(android.widget.DatePicker view, int year, int month, int day) 
        {
            if ( dialog == DIALOG_FROM_DATE_PICKER )
            {
                setFromYear = year;
                setFromMonth = month+1;
                setFromDay = day;
                txtFromDate.setText(setFromDay+("-")+setFromMonth+("-")+setFromYear);
            }
            else if ( dialog == DIALOG_TO_DATE_PICKER )
            {
                setToYear = year;
                setToMonth = month+1;
                setToDay = day;
                txtToDate.setText(setToDay+("-")+setToMonth+("-")+setToYear);
            }
        }
    };
}

фрагмент_диалога.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="5dp" >

    <TextView
        android:id="@+id/lbl_fromDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="45dp"
        android:text="From Date :"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/dialog_fromDate"
        style="@style/DropDownNav.Custom_ThemeSherlockLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/lbl_fromDate"
        android:hint="@string/lbl_select_from_date"
        android:layout_alignBottom="@+id/lbl_fromDate"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/lbl_fromDate"
        android:text="@string/lbl_select_from_date"
        android:textColor="#000000"
        android:textSize="12sp"/>

    <TextView
        android:id="@+id/lbl_toDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/lbl_fromDate"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/lbl_fromDate"
        android:layout_marginTop="22dp"
        android:text="To Date :"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/dialog_toDate"
        style="@style/DropDownNav.Custom_ThemeSherlockLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/lbl_toDate"
        android:layout_alignBottom="@+id/lbl_toDate"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/lbl_toDate"
        android:text="@string/lbl_select_to_date"
        android:textColor="#000000"
        android:textSize="12sp"/>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="81dip"
        android:layout_height="35dp"
        android:layout_below="@+id/dialog_toDate"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="OK"
        android:textColor="@color/white" />

</RelativeLayout>

style.xml - это тот же ваш код.

Я обнаружил в вашем коде, что вы получали месяц с помощью этого оператора setFromMonth = today.get(Calendar.MONDAY); или setToMonth = today.get(Calendar.MONDAY); . Я считаю, что вы сделали это по ошибке. Я также сократил ваш код, написав обычный слушатель mDateSetListener. Также имейте в виду, что Calendar.MONTH возвращает 0 для января, потому что его индекс начинается с 0. Я добавляю +1 в прослушиватель, прежде чем устанавливать значение месяца для соответствующего TextView.

04.01.2014
Новые материалы

Основы Spring: Bean-компоненты, контейнер и внедрение зависимостей
Как лего может помочь нашему пониманию Когда мы начинаем использовать Spring, нам бросают много терминов, и может быть трудно понять, что они все означают. Итак, мы разберем основы и будем..

Отслеживание состояния с течением времени с дифференцированием снимков
Время от времени что-то происходит и революционизирует часть моего рабочего процесса разработки. Что-то более забавное вместо типичного утомительного и утомительного процесса разработки. В..

Я предполагаю, что вы имеете в виду методы обработки категориальных данных.
Я предполагаю, что вы имеете в виду методы обработки категориальных данных. Пожалуйста, проверьте мой пост Инструментарий специалиста по данным для кодирования категориальных переменных в..

Игра в прятки с данными
Игра в прятки с данными Я хотел бы, чтобы вы сделали мне одолжение и ответили на следующие вопросы. Гуглить можно в любое время, здесь никто не забивается. Сколько регионов в Гане? А как..

«Раскрытие математических рассуждений с помощью Microsoft MathPrompter и моделей больших языков»
TL;DR: MathPrompter от Microsoft показывает, как использовать математические рассуждения с большими языковыми моделями; 4-этапный процесс для улучшения доверия и рассуждений в математических..

Раскройте свой потенциал в области разработки мобильных приложений: Абсолютная бесплатная серия
Глава 6: Работа в сети и выборка данных Глава 1: Введение в React Native Глава 2: Основы React Native Глава 3: Создание пользовательского интерфейса с помощью React Native Глава 4:..

Все о кейсах: Camel, Snake, Kebab & Pascal
В программировании вы сталкивались с ними при именовании переменной, класса или функции. Поддержание согласованности типов и стилей случаев делает ваш код более читабельным и облегчает совместную..