I'm trying to create a layout with 6 buttons that automatically adapt to the screen size as the tiles of windows phone. In the code I create dynamically the 6 button, 2 for line but the button should fit the size of the screen filling the latter. how can I proceed?
<?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="0dip"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up" />
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up"
/>
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up"
/>
<Button
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/conv_up"
/>
</LinearLayout>
I am using the Android
.v7
libraries. This xml worked for me to create the 2 columns, 3 rows layout that fills the entire screen:I think you should take a look at GridView
Use GridLayout! This is perfect for this situation
I'd use a vertical
LinearLayout
with three rows of same weight as children, each row being a horizontalLinearLayout
having two children of same weights, which will make sure the full area is filled. For six buttons performance shouldn't be an issue.If performance is a concern, you can make the rows as
RelativeLayout
s and use a strut to split in half and position the two children based on that.When I say a strut, I mean this:
Update: Since you're trying the
LinearLayout
s, here's how you can deal with the heights and widths:The parent
LinearLayout
can have:The three
LinearLayout
children will have:The
Button
s will have:As you can notice, we have
0dip
for the property that weight is applied on (either on height if parent is vertical oriented, or width if parent is horizontal oriented), which will need to grow to fill in the space.Here's the full XML (buttons don't include drawables, so feel free to add yours):
And the result: