Rilcon42 Rilcon42 - 1 year ago 102
Android Question

Scaling dynamic button

I am trying to add a large number of buttons in a row to a screen. The buttons are set in a TableLayout. I have searched multiple places like this:
Calculate screen size in android trying to find a way to set the size of multiple buttons (between 1 and 9) so that they will all fit on one screen. The buttons are created dynamically like this:

// put values into btn array
for (int i = 0; i < row; i++) {
tr = new TableRow(this);
for (int j = 0; j < col; j++) {
b = new Button(this);
b.setText(bArray[j][i] + "");
b.setTag(j + "," + i);

Note: the vars row and col are set to the same value (a number 1 through 9). The TableLayout is set inside a RelativeLayout in xml like this:

<RelativeLayout xmlns:android=""
tools:context=".MainActivity" >

android:layout_alignParentTop="true" >


EDIT: the buttons are going horizontally.

Answer Source

Well, you can do a lot of different things. It is hard to tell exactly what you are going for from your question but I will throw out some options. (I don't know what way these buttons are going, so I am assuming vertical)

  1. A simple way is to find the height and divide it by the number of buttons. Something along the lines of b.setHeight(this.getHeight()/numButtons)

  2. You can simply apply a wrap content attribute to the height of the buttons. This will simply take up the minimum needed space.

  3. Use a ScrollView so that you don't have to worry about heights at all.

  4. Lastly, you can set each of the buttons to match_parent and set each of their layout_weight's equal. I would recommend this method. Its probably the easiest and least error prone.

Carification on #4

With the buttons going horizontally, you are going to want to set the width of the buttons to MATCH_PARENT and the layout_weight to a constant number (eg 0.5). This will make all of the buttons expand across the parent with an equal width.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download