Reputation: 2390
I am trying to display 9 images on my screen in 3x3 matrix format so that it fits to screen perfectly. I am able to get the desired result using xml, but I am not able to replicate the same by creating controls through code. (3 columns fit to my screen perfectly but the rows are not resizing to fit to screen) Please suggest a way through which I can create dynamic controls through code and get the desired results.
Note : I want everything to fit in my screen in a matrix format, but without scrollbars. (I was unable to achieve this using grid layout)
Here is my xml :
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<TableRow
android:gravity="center"
android:layout_weight="1">
<ImageView
android:layout_width="1dp"
android:layout_height="match_parent"
android:src="@drawable/icon"
android:layout_weight="1"
android:layout_gravity="center"/>
<ImageView
android:layout_width="1dp"
android:layout_height="match_parent"
android:src="@drawable/encrypt"
android:layout_weight="1"
android:layout_gravity="center"/>
<ImageView
android:layout_width="1dp"
android:layout_height="match_parent"
android:src="@drawable/gear"
android:layout_weight="1"
android:layout_gravity="center"/>
</TableRow>
<TableRow
android:gravity="center"
android:layout_weight="1">
.
.//Same as row 1
</TableRow>
<TableRow
android:gravity="center"
android:layout_weight="1">
.
.//Same a row 1
</TableRow>
</TableLayout>
This produces an output in matrix format, resizing cells to fit to screen.
But I am not able to replicate the same result when I am creating controls through code. This is code that I am using :
TableLayout simple_game = new TableLayout(this);
simple_game.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT));
for(int i=0;i<3;i++)
{
TableRow tr = new TableRow(this);
simple_game.addView(tr);
TableLayout.LayoutParams trPara = new TableLayout.LayoutParams();
trPara.weight = 1f;
trPara.gravity = Gravity.CENTER;
tr.setLayoutParams(trPara);
for(int j=0;j<3;j++)
{
ImageView iv = new ImageView(this);
iv.setImageResource(I[i][j]);
tr.addView(iv);
TableRow.LayoutParams trPara2 = new TableRow.LayoutParams();
trPara2.width = 1;
trPara2.height = ViewGroup.LayoutParams.MATCH_PARENT;
trPara2.weight = 1f;
trPara2.gravity = Gravity.CENTER;
iv.setLayoutParams(trPara2);
}
}
setContentView(simple_game);
Using this code, the columns are resizing themselves to fit to screen but the rows are not resizing.
Upvotes: 1
Views: 1776
Reputation: 38
The answer is LinearLayout and the weight attribute. You can:
Note: weight doesn't work well with grid layout until API level 21 or 22, so if that is your target grid layout might be the way to go.
This explains creating layouts dynamically.
Upvotes: 1