gpt4 book ai didi

android - 使用 getResources().getIdentifier 对 4 个按钮进行平方

转载 作者:行者123 更新时间:2023-11-29 21:46:56 31 4
gpt4 key购买 nike

我想在表格布局正方形中制作 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" />

到目前为止一切看起来都很好。现在我想获取每个 Button 的 witdh 并将该值设置为其高度。

我的代码:

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

希望它有用...

关于android - 使用 getResources().getIdentifier 对 4 个按钮进行平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15535471/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com