Skip to content Skip to sidebar Skip to footer

Implementing Datepicker In Fragment

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 DatePicker. which isn

Solution 1:

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

DialogFragmentpicker=newDatePickerFragment();
picker.show(getFragmentManager(), "datePicker");

DatePickerFragment.java

publicclassDatePickerFragmentextendsDialogFragmentimplementsDatePickerDialog.OnDateSetListener {


@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the pickerfinalCalendarc= Calendar.getInstance();
intyear= c.get(Calendar.YEAR);
intmonth= c.get(Calendar.MONTH);
intday= c.get(Calendar.DAY_OF_MONTH); 

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

@OverridepublicvoidonDateSet(DatePicker view, int year, int month, int day) {
Calendarc= Calendar.getInstance();
c.set(year, month, day);

SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
StringformattedDate= sdf.format(c.getTime());    
}
}

Solution 2:

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.

Solution 3:

. . . 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.

Post a Comment for "Implementing Datepicker In Fragment"