2

在我的申请中,我需要将年龄限制设置在7-18 岁之间。我想显示选项范围有限的日期选择器。

如何使用此代码DatePicker将同一任务编辑到日期选择器中

我正在使用下面的代码来限制年份,但是当单击“+/-”按钮时,年份可以在限制范围之上/之下进行更改。我希望该用户不能增加或减少日期值。

 return new DatePickerDialog(this,
                                mDateSetListener,
                                mYear-7, mMonth, mDay);

请帮助我将生日的日期限制设置在 7-18 岁之间,如果可能的话,设置日期和月份。

另外,如何设置最小年龄限制?

谢谢。

4

1 回答 1

7

经过这么多时间,我终于得到了解决方案。

 @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;
}
 }
于 2012-10-17T06:28:09.243 回答