我按下了一个按钮来打开日期和时间选择器,但必须选中CheckBox才能激活我的按钮。没有复选框,它工作正常,chekbox选中或取消选中,它不会打开日期选择器。你能告诉我为什么吗?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
pick_date = (Button) findViewById(R.id.pick_date);
tv_result = (TextView) findViewById(R.id.tvdate_result);
CheckBox fixed_date_flag = (CheckBox) findViewById(R.id.fixed_date);
final boolean checked = (fixed_date_flag).isChecked();
if(checked){
pick_date.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day);
datePickerDialog.show();
}
});}
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
yearFinal = year;
monthFinal = month + 1;
dayFinal = dayOfMonth;
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(NewActivity.this, NewActivity.this, hour, minute, DateFormat.is24HourFormat(this));
timePickerDialog.show();
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
hourFinal = hourOfDay;
minuteFinal = minute;
tv_result.setText(
"year: " + yearFinal + "\n" +
"month: " + monthFinal + "\n" +
"day: " + dayFinal + "\n" +
"hour: " + hourFinal + "\n" +
"minute: " + minuteFinal);
}
}
答案 0 :(得分:0)
你的问题非常简单:
创建活动时,您正在检查是否选中了复选框。如果此值为true(但不是true),则向datePicker添加单击侦听器。所以,选择器没有点击监听器!这意味着当你"点击"即使选中了复选框,它也没有添加监听器。
您必须在onClick方法中移动if语句,如下所示:
编辑:
pick_date.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if((fixed_date_flag).isChecked()){
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day);
datePickerDialog.show();
}
}
});
尽管如此,我认为创建一个实现OnClickListener接口的分离cass是一个更好的选择,所以在构造函数中你可以初始化datepicker,instanciated作为这个新类的私有变量,并且你只能调用onClick方法to .show()方法(如果选中复选框,obbiusly)
希望它有所帮助!