Search code examples
androidandroid-fragmentsandroid-datepicker

Android how to show DatePicker in Fragment?


I am new on Android Fragments and I want to know that how can I show or implement DatePicker in simple Fragmentand not a FragmentActivity.

For example my class name is:

public class FragmentAddCard extends Fragment {
}

Thanks.


Solution

  • In your button click call the DateFragment like this

       dob.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
    
                DialogFragment newFragment = new SelectDateFragment();
                newFragment.show(getFragmentManager(), "DatePicker");
    
            }
        });
    

    Here is the code snippet for DateFragment

      public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
            }
    
            public void onDateSet(DatePicker view, int yy, int mm, int dd) {
                populateSetDate(yy, mm+1, dd);
            }
            public void populateSetDate(int year, int month, int day) {
                dob.setText(month+"/"+day+"/"+year);
                }
    
        }