Skip to content Skip to sidebar Skip to footer

How To Set Button Width Dynamically At Runtime To Fill The Screen?

I am learning android development and I am trying to fill the screen with six buttons. But I want to set the button size dynamically. I am getting screen size using final DisplayMe

Solution 1:

Use linearlayout and weight to display 6 buttons with equal width.

<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:weightSum="6" ><Buttonandroid:layout_height="wrap_content"android:padding="10dip"android:layout_weight="1" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1" /></LinearLayout>

Solution 2:

@vipul mittal has the answer if you do not need to set it programmatically. However, since you asked "what am I doing wrong" also, you do not set Button widths using dp - it's pixels.

So, when you get the display metrics just divide the pixels by 6 like this:

button.setWidth((int) (displayMetrics.widthPixels/6));

Solution 3:

Using Linear Layout will best option in the XML. Like this:

<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:weightSum="1" >

     <Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="0.15" /><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="0.15" />// Other buttons and texview in similar way. Total sum of android:layout_weight values need to be 1.
  </LinearLayout>

It seems you are more interested to do it in TableLayout and 6 buttons and 1 TextView in each row. I would you do change things in xml in this way:

<TableLayoutandroid:id="@+id/tableLayout1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:shrinkColumns="*"android:stretchColumns="*" ><TableRowandroid:id="@+id/tableRow1"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_horizontal" ><Buttonandroid:id="@+id/button1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:layout_span="3" /><Buttonandroid:id="@+id/button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:layout_span="3" />

                    // Other buttons and texview in similar way

            </TableRow>

Post a Comment for "How To Set Button Width Dynamically At Runtime To Fill The Screen?"