需要將四個按鈕分布在四方形的表布局中,button如下:
<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" />
運行很好,現在我想獲取每個button的寬度然後設置它的高度。
@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.
}