Implementing DatePicker in Fragment

后端 未结 3 1416
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 17:53

I\'am using Fragment which is an instance of Fragment and not of DialogFragment.

I did google most of the search result shows how to use DialogFragment to have DateP

相关标签:
3条回答
  • 2020-12-16 18:11

    Use a DialogFragment

    If i am guessing right you want to show a DatePicker on click of buttonDate

    http://developer.android.com/guide/topics/ui/controls/pickers.html

    On Button click

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

    DatePickerFragment.java

    public class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {
    
    
    @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); 
    
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
    }
    
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
    Calendar c = Calendar.getInstance();
    c.set(year, month, day);
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String formattedDate = sdf.format(c.getTime());    
    }
    }
    
    0 讨论(0)
  • 2020-12-16 18:23

    How to implement DatePicker in Fragment?

    The same way you would "implement" a TextView in a Fragment: have onCreateView() return a View that is or contains a DatePicker. For example, you might have a layout file that contains a DatePicker widget, and have onCreateView() inflate that layout.

    0 讨论(0)
  • 2020-12-16 18:29

    . . . which isn't working in my case because of type mismatch of Fragment and DialogFragment

    A DialogFragment IS-A Fragment because it extends Fragment.Therefore, you can use a DialogFragment anywhere you would a Fragment.

    0 讨论(0)
提交回复
热议问题