升级依赖库后TextInputLayout搭配TextInputEditText的ems属性失效
这是Material Components组件库升级到1.1.0及以上版本后的默认行为调整:TextInputLayout 默认不再读取子级TextInputEditText的ems属性作为自身宽度的测量依据,父布局宽度计算失效后,子控件的ems自然不会生效。
有两种通用的修复方案:
- 方案一:直接将
ems属性移到TextInputLayout上
新版本TextInputLayout自身支持ems属性,会直接按照配置的数值计算宽度,修改后的代码如下:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/til" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:hint="Some hint" android:ems="7" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="parent"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/tiet" android:layout_width="match_parent" android:layout_height="match_parent" android:autofillHints="Some Hint" android:imeOptions="actionNext" android:importantForAutofill="yes" android:inputType="text" /> </com.google.android.material.textfield.TextInputLayout>
- 方案二:保留子控件的ems配置,给
TextInputLayout开启子控件测量规则
添加app:measureWithLastChild="true"属性,让TextInputLayout测量宽度时优先使用子TextInputEditText的测量结果,这样原来子控件的ems配置就会生效:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/til" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:hint="Some hint" app:measureWithLastChild="true" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="parent"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/tiet" android:layout_width="match_parent" android:layout_height="match_parent" android:autofillHints="Some Hint" android:imeOptions="actionNext" android:importantForAutofill="yes" android:inputType="text" android:ems="7" /> </com.google.android.material.textfield.TextInputLayout>
如果修改后还是出现宽度不符合预期的情况,可在TextInputLayout上额外添加android:minWidth="0dp"和app:boxMinWidth="0dp",覆盖组件默认的最小宽度配置即可。
内容的提问来源于stack exchange,提问作者Avinta
相关产品推荐
相关产品推荐

