我做了日期选择的,要有两个按钮“确认”和“取消”。
我想达到的效果是按“取消”关闭弹出的日期选择对话框,按“确认”关闭弹出的日期对话框同时把选择的日期写到textview中。
但是现在不管我按“取消”还是“确认”,日期都会写到textview中。怎么解决?
“取消”和“确认”的单击事件跟onDateSet有什么关联?
还有如果我在onDateSet中写toast弹出信息汇报“Unfortunately,test01 has stopped.”错,这又是为什么呢?
private DatePickerDialog.OnDateSetListener DatePickerListener = new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.textview1);
textview.setText(year+"-"+monthOfYear+"-"+dayOfMonth);
}
};
DatePickerDialog picker = new DatePickerDialog(MainActivity.this, DatePickerListener,
iYear, iMonth, iDay);
picker.setCancelable(true);
picker.setCanceledOnTouchOutside(true);
picker.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Picker", "Correct behavior!");
}
});
picker.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Picker", "Cancel!");
}
});
picker.show();
------解决方案--------------------
抱歉,没看清。你可以加一个boolean标志位,
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
if(flag){
textview=(TextView)findViewById(R.id.textview1);
textview.setText(year+"-"+monthOfYear+"-"+dayOfMonth);
}
}
picker.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Picker", "Correct behavior!");
flag = true;
}
});
picker.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
@Override