Rob85
Rob85

Reputation: 1729

Is there a way to use weights with both layout width and height

I have a layout which has four buttons spread along the bottom of my app using the layout weight to distribute them evenly.

I also want to increase the hight of the buttons using the same sort of weighting.

So far all i can see is either calculating the width with a horizontal linearlayout or height using a vertical linearlayout.

the width is working great its just the height.

If the weight cannot be used at the same time how can i set the height so that it is relative on every screen size.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:weightSum="1.0" 
    android:gravity="bottom">

    <ImageButton
        android:id="@+id/Button1"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_weight="0.25"
        android:src="@drawable/b1"
        android:text="Left" />

    <ImageButton
        android:id="@+id/Button2"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_weight="0.25"
        android:src="@drawable/b2"
        android:text="RotL" />

    <ImageButton
        android:id="@+id/Button3"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_weight="0.25"
        android:src="@drawable/b3"
        android:text="RotR" />

    <ImageButton
        android:id="@+id/Button4"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_weight="0.25"
        android:src="@drawable/b4"
        android:text="Right" />

  </LinearLayout>

I dont want to hardcode the heights of the buttons

Upvotes: 5

Views: 2842

Answers (2)

JavierSP1209
JavierSP1209

Reputation: 899

Just for adding, you must take into account layout optimization, as said on (http://developer.android.com/training/improving-layouts/optimizing-layout.html) you should never use nested weights because they are so expensive as each child needs to be measured twice.

In my case i could try GridLayoutInstead, or a RelativeLayout to accomplish the result you want.

Upvotes: 1

BVB
BVB

Reputation: 5420

  1. Set your Buttons' heights to fill_parent
  2. Place your horizontal LinearLayout in a vertical LinearLayout
  3. Set the horizontal LinearLayout's weight <- this is now a vertical weight that will affect your Buttons' heights

The buttons should resize correctly

Upvotes: 5

Related Questions