WeightSum在android中的LinearLayout中没有按预期工作

时间:2017-09-09 14:56:59

标签: android android-layout-weight

好吧,我有一个有两个孩子的LinearLayout,一个EditText和一个Button,他们都有 weightSum 3 。我想要的是使用2 layout_weight EditText和1 layout_weight按钮的水平线。这是我的代码:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:weightSum="3">

    <EditText
        android:id="@+id/edit1"
        android:inputType="textAutoComplete"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/DBLocations"
        android:layout_weight="1"/>
</LinearLayout>

但是重量不起作用,结果如下: screenshot of the wrong result 为了在EditText中使用2 layout_weight而在Button中使用1,我需要做些什么?

2 个答案:

答案 0 :(得分:2)

您应该在XML代码中设置android:orientation="horizontal"

android:layout_width="0dp"Button中添加EditText

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal
    android:weightSum="3">

<EditText
    android:id="@+id/edit1"
    android:inputType="textAutoComplete"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"/>
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="@string/DBLocations"
    android:layout_weight="1"/>
</LinearLayout>

答案 1 :(得分:0)

制作&#39; layout_width&#39; as&#39; 0dp&#39;对于Button并将LinearLayout的方向设置为horizontal,如图所示

<LinearLayout android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal 
    android:weightSum="3"> 

    <EditText android:id="@+id/edit1" 
        android:inputType="textAutoComplete" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight="2"/> 

    <Button android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:text="@string/DBLocations" 
        android:layout_weight="1"/> 
</LinearLayout>