Jonas Jonas - 11 months ago 59
Android Question

Squaring 4 Buttons with getResources().getIdentifier

I want to make 4 Buttons in a Table layout square.

The Buttons look like that (id is counting up to 4):

android:text="Button1" />

Everything looks fine so far.
Now I want to get the witdh of each Button and set that value as its height.

My code:

public void onWindowFocusChanged(boolean hasFocus) {

for (int i = 0; i <= 4; i++) {

String buttonID = "button" + i;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
Button b = (Button) findViewById(resID);
int width = b.getWidth();


But that crashes... WHY?

Please help me.

Answer Source

try and make your button as below

Button[] buttons; 
for(int i=0; i<4; i++) {
 String buttonID = "button" + (i+1);

 int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
 buttons[i] = ((Button) findViewById(resID));
 //set your height and width as you are doing.

hope it works...