How to Make Two Buttons Take 50% Width in Android Layout

If you are not just yet very familiar with Android SDK, how its components work and what properties mean – you may find yourself struggling trying to do very simple things like having two buttons on the screen, each taking half of it horizontally. First, and if you have not already done so, you want to drop the LinearLayout (Horizontal) on your layout. This will create something similar to the following code in your layout:

<LinearLayout
	android:id="@+id/linearLayout1"
	android:layout_width="match_parent"
	android:layout_height="wrap_content" >
</LinearLayout>

Now, go ahead and drop two buttons on that layout. The buttons will left-align by default and the width will be determined by the length of the text:

<LinearLayout
	android:id="@+id/linearLayout1"
	android:layout_width="match_parent"
	android:layout_height="wrap_content" >

	<Button
		android:id="@+id/button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Button1" />

	<Button
		android:id="@+id/button2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Button2" />

</LinearLayout>

This is what it would look like in the graphical layout:

The magic property you are looking for is called Layout weight. This property determines the size ratio of elements in layouts. In our particular case, we have two buttons placed in a horizontal layout. Despite of you may be guessing, the value of this property on each button is not going to be 0.5 – it will be 1. While 0.5 is a logical thought, 0.5 x 2 buttons being 1, you have to look at this the other way around – think of all components your layout contains and the sum of their weights being 100% of your layout. In our example, the first button takes 1 part and the second button takes 1 part as well – so we have 2 parts total making up 100% the layout width. Thus, each 1 part is 50%. As another example, if you wanted your first button to be 3/4 of the width and the second one 1/4 – you would set the weight to 3 and 1 respectively.

So, in order to have the buttons take up 50% of the layout total width, you would need this:



	

You can set the Layout weight property in the Properties window or type it in directly in your layout XML file. By setting the value to 1 in the example above, this is what you will get in your graphical layout:

This entry was posted in Android and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *