通过代码设置TextInputEditText值后,Hint仍显示在背景的问题求助
问题原因及解决方法
核心问题
你给TextInputEditText设置了android:focusableInTouchMode="false",导致输入框无法获取焦点。Material Components的TextInputLayout提示语(Hint)上浮到边框上方的逻辑,依赖输入框的焦点状态或文本存在的状态判断。当输入框不可聚焦时,系统不会自动触发提示语的上浮行为,所以即便你设置了文本,提示语仍会停留在背景位置。
解决方案
方案1:调整输入框属性(推荐)
移除TextInputEditText的android:focusableInTouchMode="false"属性,如果需要让输入框不可编辑,改用以下方式实现:
- 布局中添加
android:editable="false"(适配旧版本)或android:inputType="none" - 或在代码中设置
binding.autocomplete.isEnabled = false
修改后的布局示例:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/textLayoutAutocomplete" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/standort" android:layout_weight="1"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/autocomplete" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:editable="false" /> </com.google.android.material.textfield.TextInputLayout>
方案2:手动触发提示语状态更新
如果必须保留focusableInTouchMode="false",可以在设置文本后强制更新TextInputLayout的状态:
binding.autocomplete.setText(place.toString()) // 强制更新布局,触发提示语上浮 binding.textLayoutAutocomplete.requestLayout() // 或手动更新输入框状态 binding.textLayoutAutocomplete.updateEditTextState()
内容的提问来源于stack exchange,提问作者Captai-N
相关产品推荐
相关产品推荐

