Step 1 : create activity.xml
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edttext" />
Step 2 : Create the DatePickerFragment.class
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener { DatePickerFragment mInstance; public interface DateListener { void onDateSelected(int year, int month, int day); } DateListener mDateListener; public void setCallBack(DateListener dateListener) { this.mDateListener = dateListener; } public void DatePickerFragment(DatePickerDialog.OnDateSetListener m) { mInstance = this; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -18); 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); } public void onDateSet(DatePicker view, int year, int month, int day) { mDateListener.onDateSelected(year, month, day); } }
Step 3: Main Activity
ettext.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { showDatePickerDialog(); } });
Step 4 : Main Activity
private void showDatePickerDialog() { DatePickerFragment newFragment = new DatePickerFragment();// newFragment.show(getSupportFragmentManager(), "datePicker");
newFragment.show(getFragmentManager(), "datePicker"); newFragment.setCallBack(mDateListener); }private DatePickerFragment.DateListener mDateListener = new DatePickerFragment.DateListener() { public void onDateSelected(int year, int month, int day) { Calendar c = Calendar.getInstance(); c.set(year, month, day); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); String formattedDate = sdf.format(c.getTime()); ettext.setText(formattedDate);
/* java.util.Calendar c = java.util.Calendar.getInstance();
c.set(year, month, day); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy"); String formattedDate = sdf.format(c.getTime()); editBirthdate.setText(formattedDate); */
} };
No comments:
Post a Comment