我有两个EditText,如下:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:weightSum="1"
android:orientation="horizontal">
<EditText
android:id="@+id/edtTxtNameReg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="text"
android:layout_weight="0.5"
android:hint="Name"/>
<EditText
android:id="@+id/edtTxtSurNameReg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="text"
android:layout_weight="0.5"
android:hint="Surname"/>
</LinearLayout>
在我用edtTxtNameReg编写时,它的宽度增加了,而edtTxtSurNameReg的宽度减小了。
是否有一种方法可以保持edtTxtNameReg宽度不变,文本向左滚动?
谢谢
发布于 2017-07-21 20:56:25
同时对android:layout_width="0dp"
使用EditText,宽度不会随内容而变化
对于LinearLayout,当使用android:layout_weight
时,水平方向的宽度或垂直方向的高度必须是="0dp"
发布于 2017-07-21 21:49:56
Tonteria24说的大多数都是正确的,但这部分不正确:
对于
LinearLayout
,当使用android:layout_weight
时,水平方向的宽度或垂直方向的高度必须是="0dp"
layout_weight
在LinearLayout
中的工作方式是:
为LinearLayout
中的所有视图赋予0dp
大小和等权值是非常常见的,或者给出一个视图的0dp
大小和1
权重。这是有意义的,因为它基本上跳过了我上面的第一点(孩子要求的是0宽或高),然后平均地划分空间。
然而,将wrap_content
和layout_weight
结合起来是完全有效的。
但是,它会导致不同的行为。首先,LinearLayout
将给第一个EditText
足够的宽度来包装它的内容,然后它将(尝试)给第二个EditText
足够的宽度来包装它的内容,然后它将在这两个视图之间划分任何额外的空间。
结果是什么呢?随着第一个EditText
内容的宽度增加,用于分隔的“额外”空间会缩小。如果输入足够多的文本,第一个EditText
最终会增长到填充整个LinearLayout
。
这就是为什么将其宽度设置为0dp为您解决这个问题的原因。它阻止了日益增长的行为。但是,可能会有另一次您想要同时使用wrap_content
和layout_weight
的时候,这是非常好的。
https://stackoverflow.com/questions/45246513
复制相似问题