簡體   English   中英

用建議的日期打開DatePicker

[英]Open DatePicker with suggested date

我需要基於GregorianCalendar的YEAR-MONTH-DAY_OF_MONTH屬性打開具有默認日期的DatePicker。

這是我打開DatePicker的代碼:

DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");

例如,如果我的價值觀是這樣的:

  • MyCalendar.YEAR = 2017
  • MyCalendar.MONTH = 2
  • MyCalendar.DAY_OF_MONTH = 22

打開DatePicker時設置的默認值為:

在此處輸入圖片說明

為此我必須添加什么?

基本上直接來自Android 選擇器

另外,就像任何其他的片段,您可以使用setget - Arguments將數據傳遞到片段。

詳細信息: 實例化新的Android片段的最佳做法

public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    public static DatePickerFragment newInstance(int year,int month,int day) {
        Bundle b = new Bundle();
        b.putInt("year", year);
        // put others...

        Fragment f = new DatePickerFragment();
        f.setArguments(b);
        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Update using the arguments
        Bundle args = getArguments();
        if (args != null) {
            year = args.getInt("year");
            // get others...
        }

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}

並使用該newInstance方法。

DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM