How to set min-max age limit with datepicker android

旧城冷巷雨未停 提交于 2019-12-02 05:39:28

After speanding so much time, finally I got the solution.

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
    mPickDate = (Button) findViewById(R.id.pickDate);

    mPickDate.setOnClickListener(this);

    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    maxYear = mYear - 7;
    maxMonth = mMonth;
    maxDay = mDay;

    minYear = mYear - 18;
    minMonth = mMonth;
    minDay = mDay;

    // display the current date (this method is below)
    updateDisplay(maxYear, maxMonth, maxDay);

}

private void updateDisplay(int year, int month, int day) {
    // TODO Auto-generated method stub
    mDateDisplay.setText(new StringBuilder()
            // Month is 0 based so add 1
            .append(month + 1).append("-").append(day).append("-")
            .append(year).append(" "));

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    showDialog(DATE_DIALOG_ID);

}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        /*
         * mYear = year; 
         * mMonth = monthOfYear; 
         * mDay = dayOfMonth;
         */
        // updateDisplay();



        if (year > maxYear ||monthOfYear > maxMonth && year == maxYear||
                 dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth){

            view.updateDate(maxYear, maxMonth, maxDay);
            updateDisplay(maxYear, maxMonth, maxDay);

        }
        else if (year < minYear ||monthOfYear < minMonth && year == minYear||
                 dayOfMonth < minDay && year == minYear && monthOfYear == minMonth) {

            view.updateDate(minYear, minMonth, minDay);
            updateDisplay(minYear, minMonth, minDay);
        }
        else {

            view.updateDate(year, monthOfYear, dayOfMonth);
            updateDisplay(year, monthOfYear, dayOfMonth);
        } 

    }
};

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, mDateSetListener, mYear - 7,
                mMonth, mDay);
    }
    return null;
}
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!