【问题标题】:find last day in month and using value change listener in an android app查找月份的最后一天并在 Android 应用程序中使用值更改侦听器
【发布时间】:2013-11-22 15:48:43
【问题描述】:

我正在尝试构建一个使用日期的应用程序。用户从数字选择器中选择日期。 我写了一些代码来更新选择器中的最大天数,这样用户就无法选择某个月份无法找到的日期(例如选择 2 月的 31 日)。 我不知道为什么,但我的代码不起作用。

当我选择二月时,最大天数仍然是 31。当我再次更改月份时,假设我再次选择一月,最大天数现在是 28。代码有效但有延迟

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_week);
    final NumberPicker month= (NumberPicker)findViewById(R.id.month);
    final NumberPicker day = (NumberPicker)findViewById(R.id.day);
    final Button but= (Button)findViewById(R.id.button1);
    final TextView text=(TextView)findViewById(R.id.text);
    final TextView text2=(TextView)findViewById(R.id.text2);
    final TextView text3=(TextView)findViewById(R.id.text3);
    day.setMaxValue(31);
    day.setMinValue(1);
    month.setMinValue(1);
    month.setMaxValue(12);
    month.setOnValueChangedListener(new OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            // TODO Auto-generated method stub

            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MONTH,month.getValue());
            cal.set(Calendar.DAY_OF_MONTH,1);
            int d = 0;
            while(cal.get(Calendar.MONTH)==month.getValue()){

                cal.add(Calendar.DATE, +1);
                d=d+1;


            }


            if (day.getValue()>d){
                day.setValue(d);
            }
            day.setMaxValue(d);
        }
    } );

【问题讨论】:

  • 究竟是什么不起作用?发生了什么?
  • 我将以示例回答:我选择二月的最大天数仍然是 31。当我再次更改月份时,假设我再次选择一月,最大天数现在是 28。代码有效,但使用延迟
  • 我敢打赌,您从month 获得的值是更改前的值。尝试使用参数newVal 而不是month.getValue()
  • 只是一个建议,我没有发现java calender api有多大帮助和简单,你可以看看date4j。

标签: java android calendar actionlistener onchange


【解决方案1】:

您所做的确实有效。但我认为您忘记了一个关键因素,日期和月份是 0 基于索引结帐:Calender

尝试将这些调整为:

day.setMaxValue(30);
day.setMinValue(0);
month.setMinValue(0);
month.setMaxValue(11);

【讨论】:

    【解决方案2】:

    你的问题是你调用month.getValue()会在onValueChenge()之后改变

    替换

    while(cal.get(Calendar.MONTH)==month.getValue()){
    

    由

    while(cal.get(Calendar.MONTH)==newVal-1){
    

    还有

    cal.set(Calendar.MONTH,newVal-1);
    

    【讨论】:

      【解决方案3】:

      尝试使用以下代码 sn-p 来获取一个月中的最大天数:

      int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多