42

I have a single button in a linear layout. I want the button to take up half the width of its parent. Is there a way to do this in the 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> 

My question is much like this one Assign width to half available screen width declaratively except I only have a single button.

Community
  • 1
  • 1
Kevin Westwood
  • 7,739
  • 8
  • 38
  • 52
  • possible duplicate of [Assign width to half available screen width declaratively](http://stackoverflow.com/questions/2581481/assign-width-to-half-available-screen-width-declaratively) – Saif Dec 14 '14 at 06:34

4 Answers4

80

Yep, the solution is very similar to that question, but you also want to set the weightSum of the parent LinearLayout:

<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> 
kabuko
  • 36,028
  • 10
  • 80
  • 93
5

You need to set a 0.5 (half) weight, and set the width to 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"/>
Knossos
  • 15,802
  • 10
  • 54
  • 91
1

None of these solutions worked for me on Android L. I had to do wrap_content as below:

<Button
    android:layout_gravity="center"
    android:id="@+id/btnSignin"
    android:layout_width="wrap_content"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:layout_height="wrap_content"
    android:text="@string/btn_signin"
    android:layout_marginBottom="@dimen/activity_vertical_margin" />
zeeshan
  • 4,913
  • 1
  • 49
  • 58
0

Exactly the same as the question you posted, just use a dummy view instead:

<View 
android:weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
dmon
  • 30,048
  • 8
  • 87
  • 96