Java 在android应用程序中查找月的最后一天并使用值更改侦听器
我正在尝试构建一个使用日期的应用程序。用户从数字选择器中选择日期。 我编写了一些代码,可以更新选择器中的最大天数,这样用户就无法选择某个月内找不到的日期(例如,在2月选择31天)。 我不知道为什么,但我的代码不起作用 当我选择2月份时,最大天数仍然是31天。当我再次更改月份时,假设我再次选择一月,最大天数现在是28天。代码可以工作,但会延迟Java 在android应用程序中查找月的最后一天并使用值更改侦听器,java,android,calendar,actionlistener,onchange,Java,Android,Calendar,Actionlistener,Onchange,我正在尝试构建一个使用日期的应用程序。用户从数字选择器中选择日期。 我编写了一些代码,可以更新选择器中的最大天数,这样用户就无法选择某个月内找不到的日期(例如,在2月选择31天)。 我不知道为什么,但我的代码不起作用 当我选择2月份时,最大天数仍然是31天。当我再次更改月份时,假设我再次选择一月,最大天数现在是28天。代码可以工作,但会延迟 protected void onCreate(Bundle savedInstanceState) { super.onCreate(sa
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);
}
} );
请尝试以下代码段以获取一个月的最大天数:
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
你所做的实际上是有效的。但我认为您忘记了一个关键因素:天数和月份是基于0的索引结帐: 尝试将这些调整为:
day.setMaxValue(30);
day.setMinValue(0);
month.setMinValue(0);
month.setMaxValue(11);
您的问题是您调用了
month.getValue()
,它将在onValueChenge()之后更改
替换
while(cal.get(Calendar.MONTH)==month.getValue()){
借
而且
cal.set(Calendar.MONTH,newVal-1);
到底是什么不起作用?发生了什么事?我会举个例子来回答:当我选择二月时,最多的一天仍然是31天。当我再次更改月份时,假设我再次选择一月,最大天数现在是28天。代码起作用,但延迟我打赌您从
month
获得的值是更改前的值。尝试使用参数newVal
而不是month.getValue()
只是一个建议,我还没有发现java日历api有多大帮助和简单,您可以看看date4j。
cal.set(Calendar.MONTH,newVal-1);