Last active
April 19, 2022 22:36
-
-
Save pratikbutani/036e73e26139096e3b0ba91f85e23d85 to your computer and use it in GitHub Desktop.
Using that Date Picker Universal for any view you can pick date very easily in Android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Pratik Butani | |
* | |
* Main file for Date Picker. | |
*/ | |
public class DatePickerUniversal implements View.OnFocusChangeListener, DatePickerDialog.OnDateSetListener, View.OnClickListener { | |
private EditText mEditText; | |
private Calendar mCalendar; | |
private SimpleDateFormat mFormat; | |
/** | |
* Constructor | |
* | |
* @param editText your EditText | |
* @param format give your format in which you want date like dd/MM/yyyy | |
*/ | |
public DatePickerUniversal(EditText editText, String format) { | |
this.mEditText = editText; | |
mEditText.setOnFocusChangeListener(this); | |
mEditText.setOnClickListener(this); | |
mFormat = new SimpleDateFormat(format, Locale.getDefault()); | |
} | |
@Override | |
public void onFocusChange(View view, boolean hasFocus) { | |
if (hasFocus) { | |
showPicker(view); | |
} | |
} | |
@Override | |
public void onClick(View view) { | |
showPicker(view); | |
} | |
private void showPicker(View view) { | |
if (mCalendar == null) | |
mCalendar = Calendar.getInstance(); | |
int day = mCalendar.get(Calendar.DAY_OF_MONTH); | |
int month = mCalendar.get(Calendar.MONTH); | |
int year = mCalendar.get(Calendar.YEAR); | |
new DatePickerDialog(view.getContext(), this, year, month, day).show(); | |
} | |
@Override | |
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { | |
mCalendar.set(Calendar.YEAR, year); | |
mCalendar.set(Calendar.MONTH, month); | |
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); | |
this.mEditText.setText(mFormat.format(mCalendar.getTime())); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Constructor | |
* @param editText your EditText | |
* @param format in which you want date | |
*/ | |
new DatePickerUniversal(yourDateEditText ,"dd-MMM-yyyy"); // It will return date : 18-Jun-2019 |
Works great, thank you!
Most welcome! Keep Sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works great, thank you!