【问题标题】:setting minimum Date in DatePicker在 DatePicker 中设置最小日期
【发布时间】:2016-08-08 14:15:06
【问题描述】:

大家好,我是 android 新手,遇到问题我已经搜索了很多,但没有使用 DatePickerDialog 框获得解决方案,当我运行应用程序时,虽然我设置了最小日期,但它也在选择以前的日期。我也尝试从当前时间中减去 1 秒。 DatePicker 从 1990 年 1 月开始。我希望它从今天开始并阻止以前的日期。谢谢...

public void OnButtonClickDate()

{
btn_date = (Button)findViewById(R.id.button);

edit_date = (EditText)findViewById(R.id.editText);

btn_date.setOnClickListener
(

 new View.OnClickListener() 
 {
    @Override
    public void onClick(View view) 
    {
     DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() 
     {
       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)                                                                             
       view.setMinDate(System.currentTimeMillis());
       edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
      }
    }, mYear, mMonth, mDay);
     datePickerDialog.show();
  }
}
);
}

【问题讨论】:

  • 你的格式是怎么回事?这很难阅读:(
  • 我很抱歉弄得一团糟......你想让我通过格式化将它发送到 cmets 中吗?
  • 您应该使用格式化的代码编辑您以前的帖子 - 这将增加您获得支持的里程。眨眼间,一个人可能会离开可能知道您答案的页面。

标签: android


【解决方案1】:

试着调整你的代码。

btn_date = (Button) findViewById(R.id.button);
edit_date = (EditText) findViewById(R.id.editText);
DatePickerDialog datePickerDialog = new
        DatePickerDialog(MainActivity.this,
        new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {

                datePickerDialog.setMinDate(System.currentTimeMillis());
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
            }
        }, mYear, mMonth, mDay);
datePickerDialog.setMinDate(System.currentTimeMillis());
btn_date.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog.show();
            }
        }
);

Android 日历视图是一连串的错误。如果上述方法失败,您可以尝试从选择器中删除 CalendarView。其他绕过这些bug的方法are described here

datePicker.setCalendarViewShown(false);

或者尝试使用a library 来实现此功能

    compile "com.wdullaer:materialdatetimepicker:2.4.0"

【讨论】:

  • datePickerDialog.setMinDate 给了我错误,这就是为什么我使用 DatePicker 的视图对象
【解决方案2】:

您可以使用以下代码示例在您的应用程序中设置最小日期:

 Date date = new Date();

    final long todayInMillis = date.getTime();
    final long thirteenyearMillis = 409968000000L;   
    final long eightyYearMillis = 2522880000000L;
    final long maxDate = todayInMillis - thirteenyearMillis;
    final long minDate = todayInMillis - eightyYearMillis;

希望你能从上面的示例中得到一个想法......

【讨论】:

  • 是的...谢谢你,我会尝试使用这种方法:-)
猜你喜欢
  • 2018-05-22
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多