views:

51

answers:

3

Hello,

I would like to have a layout with 5 times 5 buttons. Each of them should have the same width and height (they should be square). And I want the whole matrix to use the screen width (or height, depending on rotation).

I currently do it "by hand" in the Java code:

for (int y=0; y<5; y++) {
    TableRow tr = new TableRow(this);
    for (int x=0; x<5; x++) {
        Button b = new Button (this);
        ...
        tr.addView(b, 60, 60);
    }
    layout.addView(tr);
}

This can be improved by obtaining screen width first and then dividing by 5 to get rid of this literal 60. But I'm wondering how I can do this in the res/layout XML file?

How can I specify for the height to be the same as the width? (I can set the width to match_parent.)

Thank you.

A: 

You'll want to check out a TableLayout.

o_O how should it help?! give just a reference to that link, where he can read the answer :) i haven't found it
Mur Votema
+1  A: 

You are best off just doing this as a custom layout manager. Subclass from ViewGroup and implement the desired layout code. It is quite simple to implement a custom layout manager if you are trying to do a general-purpose layout algorithm (which you aren't). See for example the platform's AbsoluteLayout as an example of a simple layout manager: http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/widget/AbsoluteLayout.java

hackbod
A: 

I've two ideas.

Both are pretty similar to suggestion from hackbod

Instead of implementing subclass from ViewGroup, you can create something like SquareButton extending Button or SquareTableLayout extending TableLayout.

Override constructor class, so that you will replace the width or height value with the smallest value of them both. I'm not sure, but i guess, you'll be able to use new Layouts in XML-Description.

Probably it's easier to create just a SquareTableLayout

Then just set width and height of all elements within TableLayout to 0dip and the weight of all of them to 1.

Assuming that you have NxN elements in your Table, they all will get then the same width and the same height because of the same weigth.

Hope it works, I can't test it right now, I'm at home :)

Mur

Mur Votema