Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
user3555472 Avatar asked Dec 01 '14 09:12

user3555472


2 Answers

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);
            }

    }
like image 137
Don Chakkappan Avatar answered Sep 23 '22 23:09

Don Chakkappan


This is other example:

Calendar cal = Calendar.getInstance(TimeZone.getDefault()); // Get current date

// Create the DatePickerDialog instance
DatePickerDialog datePicker = new DatePickerDialog(this,
                    R.style.AppBlackTheme, datePickerListener,
                    cal.get(Calendar.YEAR), 
                                        cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH));
            datePicker.setCancelable(false);
            datePicker.setTitle("Select the date");
datePicker.show();

// Listener
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        TextView tvDt = (TextView) findViewById(R.id.tvDate);
        tvDt.setText(day1 + "/" + month1 + "/" + year1);

    }
};
like image 38
joselufo Avatar answered Sep 22 '22 23:09

joselufo