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.setOnClickListener(this);
b.setText(bArray[j][i] + "");
b.setTag(j + "," + i);
tr.addView(b);
}
table.addView(tr);
}
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="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</TableLayout>
EDIT: the buttons are going horizontally.
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)
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)
You can simply apply a wrap content attribute to the height of the buttons. This will simply take up the minimum needed space.
Use a ScrollView
so that you don't have to worry about heights at all.
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.