Reputation: 329
I have two EditText as follows:
<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>
As I write in edtTxtNameReg, its width increases and the width of edtTxtSurNameReg decreases.
Is there a way to keep the width of edtTxtNameReg constant and the text scrolling to the left?
Thanks
Upvotes: 0
Views: 1241
Reputation: 54264
Most of what Tonteria24 said is accurate, but not this part:
For
LinearLayout
whenandroid:layout_weight
is used the width for horizontal orientation or the height for vertical must be="0dp"
The way layout_weight
in LinearLayout
works is:
It is very common to give all views in the LinearLayout
a size of 0dp
and equal weights, or to give exactly one view a size of 0dp
and weight of 1
. This makes sense because it basically skips my first point above (the child asks for 0 width or height) and then divides the space up evenly.
However, combining wrap_content
and layout_weight
is perfectly valid.
But, it will cause different behavior. First the LinearLayout
will give the first EditText
enough width to wrap its content, then it will (try to) give the second EditText
enough width to wrap its content, and then it will divide any extra space between the two views.
The result? As the width of the first EditText
's contents grows, the "extra" space left over to divide shrinks. The first EditText
will eventually grow to fill the entire LinearLayout
if you enter enough text.
So that's why setting its width to 0dp solves it for you. It stops the growing behavior. But there may be another time when you want to use wrap_content
and layout_weight
together, and that's perfectly fine.
Upvotes: 1
Reputation: 4137
Use android:layout_width="0dp"
for both EditText and the width will not vary with the content
For LinearLayout when android:layout_weight
is used the width for horizontal orientation or the height for vertical must be ="0dp"
Upvotes: 3