期望:
当用户点击MaterialTextView组件时,应打开DatePickerDialog。
发生了什么事
用户需要在MaterialTextView组件上点击两次以打开DatePickerDialog。
MainActivity
protected void onCreate(Bundle SavedInstanceState){
MaterialTextView issueDate = findViewById(R.id.edIssueDate);
issueDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
hideKeyboard(AddNewCoupon.this);
DatePickerDialog datePickerDialog = new DatePickerDialog(AddNewCoupon.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
issueDate.setText(String.valueOf(dayOfMonth)+"/"+String.valueOf(month)+"/"+String.valueOf(year));
//newCustomer.hideKeyboard(AddNewCoupon.this);
}
}, year, month, day);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
}
});
}
hideKeyboard()方法:
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view == null) {
view = new View(activity);
}
if (imm != null)
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
布局:
<com.google.android.material.textview.MaterialTextView
android:id="@+id/edIssueDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:ems="10"
android:focusable="auto"
android:focusableInTouchMode="true"
android:hint="@string/txtVIssueingDtHint"
android:nextFocusDown="@id/edExpDate"
android:onClick="showDatePickerDialogForIssue"
android:paddingLeft="4dp"
android:textColor="@color/design_default_color_on_secondary"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
依赖项:
dependencies {
...
implementation 'com.google.android.material:material:1.2.0-alpha04'
...
}
在DatePickerDialog打开时,代码可以完美运行,但问题是用户需要轻按两次才能对其进行操作。我在哪里弄错了?如何修复代码?
答案 0 :(得分:1)
将 focusable 和 focusableInTouchMode 的值更改为false,可以解决问题
android:focusable="false"
android:focusableInTouchMode="false"
希望这会有所帮助!
答案 1 :(得分:0)
将文本视图更改为
<com.google.android.material.textview.MaterialTextView
android:id="@+id/edIssueDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:ems="10"
android:hint="@string/txtVIssueingDtHint"
android:onClick="showDatePickerDialogForIssue"
android:paddingLeft="4dp"
android:textColor="@color/design_default_color_on_secondary"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
答案 2 :(得分:0)
删除此选项,除非它是必需的选项。
C