Android Material 1.9.0中TextInputLayout自定义字体输入切换跳动问题
解决TextInputLayout自定义字体导致的高度跳动问题(Android 12+)
这个问题的根源是Android 12及以上版本对字体度量的处理逻辑变化,自定义字体的基线、行高与系统默认字体不匹配,导致TextInputLayout在空输入状态和有内容状态切换时,重新计算组件高度引发跳动。以下是几种可行的解决方法:
统一TextInputLayout和EditText的字体
不要仅给TextInputEditText设置自定义字体,同时将android:fontFamily属性添加到TextInputLayout上,让提示文字(hint)和输入文字使用同一种字体,消除字体度量差异带来的高度计算偏差。示例代码:<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="hint_text" android:layout_marginTop="16dp" android:fontFamily="@font/pencilstudio"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/pencilstudio" /> </com.google.android.material.textfield.TextInputLayout>使用Material属性设置精确最小高度
放弃固定数值的最小高度,改用Material Components提供的属性来定义最小高度,确保在大字体、大显示尺寸下也能适配。示例:<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="hint_text" android:layout_marginTop="16dp" android:fontFamily="@font/pencilstudio" android:minHeight="?attr/materialTextFieldBoxMinHeight"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/pencilstudio" android:minHeight="?attr/materialTextInputEditTextMinHeight" /> </com.google.android.material.textfield.TextInputLayout>调整自定义字体的度量参数(可选)
如果可以编辑字体文件,用FontForge这类工具调整字体的基线、行高、ascent/descent数值,使其与系统默认字体的度量标准匹配,从根源上避免高度计算差异。切换背景模式优化高度稳定性
尝试设置app:boxBackgroundMode为filled或outline,不同的背景渲染模式可能会让组件高度计算更稳定,减少跳动现象:<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="hint_text" android:layout_marginTop="16dp" android:fontFamily="@font/pencilstudio" app:boxBackgroundMode="filled"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/pencilstudio" /> </com.google.android.material.textfield.TextInputLayout>
内容的提问来源于stack exchange,提问作者MottaMaadi Bench
相关产品推荐
相关产品推荐

