Android开发:EditText宽度超出父TableRow无法适配如何解决?
解决方案
问题原因
- TableRow的子控件宽度规则特殊,仅设置
match_parent不会自动填充剩余宽度,需要配合layout_weight属性实现宽度分配 - 第二个存放确认密码的TableLayout未配置
android:stretchColumns="*"属性,无法自动拉伸列宽适配父布局 - EditText同时配置了
ems="10"固定字符宽度和match_parent,属性冲突导致控件宽度被撑出父布局范围 - 原有TableLayout设置了
layout_height="match_parent",会占用多余垂直空间挤压下方控件位置
修改步骤
- 给所有TableLayout补充
android:stretchColumns="*"属性,同时将TableLayout的layout_height改为wrap_content避免垂直空间占用异常 - 将所有EditText的
android:layout_width从match_parent改为0dp,新增android:layout_weight="1"属性,让TableRow自动将剩余宽度全部分配给EditText - 删除所有EditText的
android:ems="10"属性,避免固定宽度限制适配效果 - 可选:将EditText的
layout_gravity从right改为center_vertical,让输入框和左侧文字垂直对齐更美观
修改后参考代码片段
单组TableRow示例
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/novo_usuario_TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="@string/novo_usuario_texto" android:textSize="20sp" /> <EditText android:id="@+id/novo_usuario_EditText" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_margin="5dp" android:hint="Novo Usuário" android:inputType="textPersonName" android:textColorHint="@color/light_gray" android:textSize="20sp" tools:ignore="TextContrastCheck" /> </TableRow>
确认密码区域TableLayout示例
<TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:stretchColumns="*"> <!-- 内部TableRow内容参照上述示例修改即可 --> </TableLayout>
内容的提问来源于stack exchange,提问作者Laila Campos
相关产品推荐
相关产品推荐

