-UPDATE -
我按照Agarwal的建议做了,现在有这个错误:
04-21 11:42:01.807: E/AndroidRuntime(1456): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
我正在使用此代码动态设置15个按钮的宽度。并且,你猜对了,它不起作用。错误发生在for
循环中,但我不确定原因。
Button[] buttons = new Button[16];
buttons[0] = (Button)findViewById(R.id.root2);
buttons[1] = (Button)findViewById(R.id.root3);
/* blah blah blah */
buttons[13] = (Button)findViewById(R.id.root15);
buttons[14] = (Button)findViewById(R.id.root16);
LayoutParams lp = new LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
for(int x = 0; x < 16; x ++){
buttons[x].setLayoutParams(lp);
}
感谢您的帮助。 (如果有人能想出更好的方法来填充buttons[]
变量,那将非常感激。)
答案 0 :(得分:3)
for(int x = 0; x < 16; x ++){
buttons[x].setLayoutParams(lp);
}
上面的循环修复16次并且你只使用了15个按钮添加按钮或更改x&lt; 15。 如果你改变x&lt; 15然后也改变下面的
按钮[]按钮=新按钮[15];
答案 1 :(得分:1)
我已经使用它修复了它:
LayoutParams lp = new LinearLayout.LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
for(int x = 0; x < 15; x ++){
buttons[x].setLayoutParams(lp);
}
从LayoutParams
获取LinearLayout
。