Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Last active June 19, 2020 09:44
Show Gist options
  • Save Kishanjvaghela/7b8738bbb224c5f2e652 to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/7b8738bbb224c5f2e652 to your computer and use it in GitHub Desktop.
Set maximum date in DatePicker dialog
import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Calendar;
import jp.likenote.android.R;
/**
* Created by DSK02 on 8/17/2015.
*/
public class CustomDatePickerDialog extends DatePickerDialog {
int maxYear;
int maxMonth;
int maxDay;
public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
public void setMaxDate(long maxDate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getDatePicker().setMaxDate(System.currentTimeMillis());
} else {
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxDate);
maxYear = c.get(Calendar.YEAR);
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
}
}
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
} else {
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}
}
}
// Init and open dialog
private void openDatePicker() {
final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();
}
// DateSetListener
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
}
};
@arpit999
Copy link

What is myDateListener? where can i call this method?

@Kishanjvaghela
Copy link
Author

@arpit999 myDateListener is DateSetListener. You will get notify when user set date from Dialog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment