基于文本的日期输入所需的问题和字符串操作在这里似乎不值得。如果用户回到字符串的开头并开始输入会发生什么?如果用户开始输入错误的格式会发生什么?您必须考虑大量案例,而没有一种很好的方法来控制用户可以输入的内容。在这些情况下,我只会使用 DatePicker like the one in this solution。
如果您有心,您可以保留 EditText,只需设置 onClickListener 以在选中时显示 DatePicker。我建议在上面设置这两个字段:
android:cursorVisible="false"
android:focusable="false"
这样,EditText 看起来就不会像可以输入的那样。我唯一的建议或对其他答案的补充是“清除”按钮,因此可以根据需要擦除 EditText 值。为此,只需通过中性按钮添加它,如下所示:
builder.setView(dialog)
// Add action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
listener.onDateSet(null, yearPicker.getValue(), monthPicker.getValue(), 0);
}
})
.setNeutralButton(R.string.clear, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//check for a month value of -1 in onDateSet to clear current field
listener.onDateSet(null, -1, -1, 0);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MonthYearPickerFragment.this.getDialog().cancel();
}
});
然后检查是否应该清除该字段,只需执行以下操作:
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
if (i > -1){
et.setText(i1 + "/" + i);
} else {
et.setText("");
}
}