Last active
June 19, 2020 09:44
-
-
Save Kishanjvaghela/7b8738bbb224c5f2e652 to your computer and use it in GitHub Desktop.
Set maximum date in DatePicker dialog
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
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); | |
} | |
} | |
} |
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
// 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) { | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is myDateListener? where can i call this method?