Using android:layout_weight attribute

As discussed earlier i have found an temporary solution which can be used for your design to occupy your total screen space in a proportionate way. android:layout_weight attribute can be used to allocate the size of the View according to the screen size.  If we use android:layout_width=”100dp” or android:layout_width=”wrap_content” only the specified space is occupied.

Problem:

Consider that you need to place 2 buttons at the end of the screen which occupies the entire bottom part. If you use layout_width=150dp respectively for both the buttons it will look like this in 3.7″ screen and it gives an impression that the screen is occupied wisely.

Run the same code in 7″ screen even though you have used dp for setting the size of the buttons, it wont full fill your current desire. The output will look like

Solution:

Consider the bottom most part as an individual layout and add the layout_weight attribute to scale up the View elements according to the screen size.

To use layout_weight the layout_width or height of the layout must be using fill_parent

In the bellow example android:layout_width=”fill_parent” which denotes that weight is applied only to the width of the particular view not to it height. weightSum attribute take up the entire space of the layout which has to be split in an integer value, in our case we have only 2 buttons which occupies equal width, so weightSum is set to 2 and the layout_weight value of the views is specified as 1 for both the views. Each view occupies 1/2 (layout_weight/weightSum) of the space.

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”>
<LinearLayout android:layout_alignParentBottom=”true”
android:orientation=”horizontal”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:baselineAligned=”true” android:weightSum=”2″
>
<Button
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:text=”Button1″
android:layout_weight=”1″
/>
<Button
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:text=”Button2″
android:layout_weight=”1″
/>
</LinearLayout>
</RelativeLayout>

Output:

Now you are able to get the desired design across multiple screens with a single xml file. layout_weight will be a useful attribute if you use it wisely.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s