How can I give my widgets' width a percentage rather than an explicit value?

痴心易碎 提交于 2019-12-06 02:50:33

You should have a single LinearLayout containing all the "weighted" widgets.
Note that only 1 dimension at a time can be "weighted":

This is how I'd do that:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp"
    >
    <Spinner
        android:id="@+id/spinnerUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".40"
        android:entries="@array/delivery_upcplu_spinner"
    />
    <EditText
        android:id="@+id/editTextUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".60"
        android:editable="false"
    />
</LinearLayout>

Note that the weight sum is 1 (android calculates it by itself).
I could set 4 and 6 or 40 and 60 - for Android that's always 100%, when summed.

You can optionally set a weightSum attribute in the Containing LinearLayout:

android:weightSum="1"

(or 10, or 100, ...)

If you want to (and your layout isn't complex), you can weight the other "dimension" (height in this case), too.

Just add another LinearLayout containing another Spinner and EditText.

Then enclose these 2 LinearLayouts in a third one.

Give both the children LinearLayouts a weight of 1 and a height of 0dp, so they will equally divide the container's height.

Some thing like that:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp"
    >
    <Spinner
        android:id="@+id/spinnerUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:entries="@array/delivery_upcplu_spinner"
    />
    <EditText
        android:id="@+id/editTextUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:editable="false"
    />
</LinearLayout>

or

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp"
    >
    <Spinner
        android:id="@+id/spinnerUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="70"
        android:entries="@array/delivery_upcplu_spinner"
    />
    <EditText
        android:id="@+id/editTextUPCPLU"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="30"
        android:editable="false"
    />
</LinearLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!