Android set layout_weight to width in vertical LinearLayout

2.9k views Asked by At

I got a vertical LinearLayout, in which there's a button. I want to make this button 70% of the width of the LinearLayout and center it.

I've tried setting layout_weight to 0.7 while setting the layout_width to 0, but since it's a vertical LinearLayout, it doesn't affect the width, but can only affect the height.

How can I change the weight of the width in a vertical layout? Will I must add a nesting horizontal LinearLayout just for the button so I can set its weight?

4

There are 4 answers

4
Jozef Dochan On BEST ANSWER

Try using new PercentRelativeLayout, and you can achieve what you are trying without nested layouts.

include this in your dependencies :com.android.support:percent:25.1.0

And then in your code

<android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  ...

 <Button
       app:layout_widthPercent="70%"
       android:layout_height="wrap_content"/>
  ...

</android.support.percent.PercentRelativeLayout>
0
Chandan kushwaha On

Please check this out.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.7"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/yourRequiredButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:id="@+id/container"
        android:layout_weight="0.3"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

</LinearLayout>
0
Ari M On

Try this:

<LinearLayout>
    <Space android:layout_weight=0.15/>
    <Button android:layout_weight=0.7/>
    <Space android:layout_weight=0.15/>
</LinearLayout>

https://developer.android.com/reference/android/widget/Space.html

I also suggest you put the values in dimens.xml file.

3
Matias Elorriaga On
linearLayout -> orientation = horizontal
button -> layout width = 0dp
       -> layout height = wrap_content
       -> layout weight = 1