点击Material Outlined Text Field弹出MaterialDatePicker替代系统键盘问题
问题原因
你当前的实现存在两个核心问题:
- 可点击获得焦点的实际是
TextInputLayout内部的TextInputEditText,你给外层TextInputLayout绑定的点击事件不会被触发 - EditText默认获得焦点后会自动唤起系统输入法,优先级高于你的自定义点击逻辑
解决方案
第一步:修改XML布局
给内部的TextInputEditText添加属性,禁用默认输入法唤起逻辑:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/edtStartWearLensDate" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:hint="@string/txtLabelWearSelectStartDate" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/txtLabelStartWearLensID"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/etWearDate" android:layout_width="match_parent" android:layout_height="wrap_content" <!-- 核心属性:禁用输入类型,不会唤起键盘 --> android:inputType="none" <!-- 禁用触摸时获得焦点,避免触发键盘弹出逻辑 --> android:focusableInTouchMode="false" <!-- 允许接收点击事件 --> android:clickable="true"/> </com.google.android.material.textfield.TextInputLayout>
第二步:修改Activity点击事件绑定
给实际响应点击的TextInputEditText绑定点击事件,也可以加兜底的键盘隐藏逻辑避免异常场景:
// onCreate 中修改绑定逻辑 TextInputEditText etWearDate = findViewById(R.id.etWearDate); etWearDate.setOnClickListener(view -> onEdtStartWearLensDateClick()); // 点击事件中添加兜底隐藏键盘逻辑 private void onEdtStartWearLensDateClick() { // 兜底隐藏已经弹出的键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(edtStartWearLensDate.getWindowToken(), 0); } showDatePickerDialog(); }
可以同步修改日期选择器的赋值逻辑,直接给EditText设值更稳妥:
@Override public void onPositiveButtonClick(Object selection) { etWearDate.setText(materialDatePicker.getHeaderText()); }
内容的提问来源于stack exchange,提问作者Zudy
相关产品推荐
相关产品推荐

