Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android layout_weight Not Working

I am working on a fragment with 5 buttons in it. When its on a larger screen like a tablet I use a fragment that places all 5 buttons at the top. I set all their layout_width to 1 but the buttons do not spread evenly across the screen like is expected.

EXPECTED [ all ][ my ][buttons][ go ][ here ]

WHAT I GET b1 b2 b3 b4 b5 b3 and b5 are just one button... just showing it breaks one word [all][my][but ][go][her] and puts it one line down. [tons] [e ]

I have been playing with it and trying different things but I cant get it to change. Any help is appreciated. Thank you.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/xlarge_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
    android:id="@+id/tip_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/tip_button"
    android:onClick="tipButton">
</Button>

<Button
    android:id="@+id/preference"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/settings"
    android:onClick="showPreferences">
</Button>

<Button
    android:id="@+id/rate_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/rate_button"
    android:onClick="rateButton">
</Button>

<Button
    android:id="@+id/feedback_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/feedback_button"
    android:onClick="feedbackButton">
</Button>

<Button
    android:id="@+id/cancel_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/exit_button"
    android:onClick="cancelButton">
</Button>
</LinearLayout>
like image 588
Jason Crosby Avatar asked Jul 20 '12 18:07

Jason Crosby


2 Answers

Short answer: set the layout_width of the buttons to 0. The layout_weight is used to determine how to spread the left-over space between the elements in a layout. Therefore, if you don't set the width to zero, the size of the content of the buttons will affect how big they are.

Here are two good blog posts explaining how weights work:

http://blog.stylingandroid.com/archives/297 http://blog.stylingandroid.com/archives/312

like image 139
Marcus Forsell Stahre Avatar answered Nov 07 '22 16:11

Marcus Forsell Stahre


Since You are using layout_weight, You should give 0dp for layout_width. It should work.

like image 8
Omar Faroque Anik Avatar answered Nov 07 '22 18:11

Omar Faroque Anik