使用getResources(). getidentifier来正方形4个按钮



我想让4个按钮在一个表格布局正方形。

按钮看起来像这样(id正在计数到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" />

到目前为止一切看起来都很好。现在我想获得每个按钮的宽度,并将该值设置为其高度。

我代码:

@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);
    }
}

但是崩溃了…为什么?

请帮帮我。

试着让你的按钮如下

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

希望它能起作用…

最新更新