Jonas Jonas - 21 days ago 13
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):

<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_column="0"
android:background="@drawable/tile_selector"
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:

@Override
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();
b.setHeight(width);
}

}


But that crashes... WHY?

Please help me.

Answer

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...

Comments