按钮半宽屏幕

Kev*_*ood 41 android android-layout

我有一个线性布局的按钮.我希望按钮占据其父级宽度的一半.有没有办法在布局xml中执行此操作.

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    android:padding="6dp">

    <Button
        android:id="@+id/buttonCollect"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="@string/hello"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"/>

</LinearLayout> 
Run Code Online (Sandbox Code Playgroud)

我的问题非常类似于将声明宽度分配给可用屏幕宽度的一半,除了我只有一个按钮.

kab*_*uko 78

是的,解决方案与该问题非常相似,但您还需要设置父LinearLayout的weightSum:

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    android:padding="6dp"
    android:weightSum="2">

    <Button
        android:id="@+id/buttonCollect"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/hello"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:layout_weight="1" />

</LinearLayout> 
Run Code Online (Sandbox Code Playgroud)

  • 哦,是的,如果你真的想要一半,从其他人提到的0dp宽度开始通常是一个好主意. (2认同)

Kno*_*sos 5

您需要设置 0.5(一半)的权重,并将宽度设置为 0。

<Button
    android:id="@+id/buttonCollect"
    android:layout_width="0dip"
    android:layout_weight="0.5"
    android:layout_height="match_parent"
    android:text="@string/hello"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"/>
Run Code Online (Sandbox Code Playgroud)