I want to show date picker popup window. I have found some examples but I am not getting it properly. I have one edit text and I click on edit text the date picker dialog should pop up and after setting the date, the date should show in edit text in dd/mm/yyyy format in fragments. PLease provide me sample code or good links.
Solution:
Make your EditText clickable and focusable false
like,
<EditText
android:id="@+id/etDOB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:hint="Select" />
Then in your Fragment Class, put below code,
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_xxx, container, false);
EditText etDOB=view.findViewById(R.id.etDOB);
etDOB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openDatePickerDialog(v);
}
});
}
public void openDatePickerDialog(final View v) {
// Get Current Date
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
(view, year, monthOfYear, dayOfMonth) -> {
String selectedDate = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
switch (v.getId()) {
case R.id.etDOB:
((EditText)v).setText(selectedDate);
break;
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setMaxDate(cal.getTimeInMillis());
datePickerDialog.show();
}
Try this in the XML file:
<EditText
android:id="@+id/Birthday"
custom:font="@string/font_avenir_book"
android:clickable="true"
android:editable="false"
android:hint="@string/birthday"/>
Now in Java File:
Calendar myCalendar = Calendar.getInstance();
EditText edittext= (EditText) findViewById(R.id.Birthday);
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
edittext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(classname.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
Now add the method in the above activity.
private void updateLabel() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
edittext.setText(sdf.format(myCalendar.getTime()));
}
Add android:focusable="false"
within the xml file of the EditText to allow for a single touch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With