为什么日期对话框要求单击三次以解除

时间:2012-12-12 13:21:10

标签: android datepicker

public class QuickIWantActivity extends Activity implements
        OnDateSetListener {
.....
.....
.....

dateET.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
        QuickIWantActivity.this, QuickIWantActivity.this, cal
            .get(Calendar.YEAR), cal.get(Calendar.MONTH),
        cal.get(Calendar.DAY_OF_MONTH));
        datePickDiag.show();
        return true;
        }
    });

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {

    int month = monthOfYear + 1;
    dateET.setText(dayOfMonth + "- " + month + "- " + year);
}

}

所以在触摸dateET这是一个EditText它会打开datepicker,我设置新的日期并点击设置,它不会被解雇,我再次点击设置,即使现在它也不会被解雇,最后它被解雇当我点击第3次设置

1 个答案:

答案 0 :(得分:3)

onTouch收到三个事件(正常序列):

MotionEvent.ACTION_DOWN
MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP

由于你没有检查它们(并且返回true),你的代码执行3次(每个事件一个)。

解决方案:

使用onClick()(这就是我要做的)或添加支票:

@Override
public boolean onTouch(View v, MotionEvent event) {

switch (event.getAction()) { 
  case MotionEvent.ACTION_DOWN:

Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
        QuickIWantActivity.this, QuickIWantActivity.this, cal
            .get(Calendar.YEAR), cal.get(Calendar.MONTH),
        cal.get(Calendar.DAY_OF_MONTH));
        datePickDiag.show();
        return false;
        }
    });
break;
}