在 android 中使用 getResources().getIdentifier() 获取可绘制对象
Obtain a drawable with getResources().getIdentifier() in android
我想以编程方式调整按钮数组中几个按钮的背景。这样做时,我想 assemble 来自字符串和数字的标识符。
对于 strings.xml
中的文本资源,我已经能够在功能上将其组合在一起:
basicDEGR[g].setVoc(getResources().getIdentifier("vocGR" + (g +((category-1)*20)), "string", getPackageName()));
不幸的是,与可绘制对象类似的方法不起作用:
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
Button button7 = (Button) findViewById(R.id.button7);
Button button8 = (Button) findViewById(R.id.button8);
Button button9 = (Button) findViewById(R.id.button9);
Button button10 = (Button) findViewById(R.id.button10);
Button[] button = new Button[] {button1, button2, button3, button4, button5, button6, button7, button8, button9, button10};
for (int i = 1; i<11; i++)
{
button[i].setBackground(getResources().getIdentifier("gr" + i, "drawable", this.getPackageName()));
}
目前我遇到这种错误:
error: incompatible types: int cannot be converted to Drawable
button[i].setBackground(getResources().getIdentifier("gr" + i, "drawable", this.getPackageName()));
^
什么是正确的方法?
Use setBackgroundResource()
使用给定资源 ID 的可绘制(或颜色)资源设置背景。
我想以编程方式调整按钮数组中几个按钮的背景。这样做时,我想 assemble 来自字符串和数字的标识符。
对于 strings.xml
中的文本资源,我已经能够在功能上将其组合在一起:
basicDEGR[g].setVoc(getResources().getIdentifier("vocGR" + (g +((category-1)*20)), "string", getPackageName()));
不幸的是,与可绘制对象类似的方法不起作用:
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
Button button7 = (Button) findViewById(R.id.button7);
Button button8 = (Button) findViewById(R.id.button8);
Button button9 = (Button) findViewById(R.id.button9);
Button button10 = (Button) findViewById(R.id.button10);
Button[] button = new Button[] {button1, button2, button3, button4, button5, button6, button7, button8, button9, button10};
for (int i = 1; i<11; i++)
{
button[i].setBackground(getResources().getIdentifier("gr" + i, "drawable", this.getPackageName()));
}
目前我遇到这种错误:
error: incompatible types: int cannot be converted to Drawable
button[i].setBackground(getResources().getIdentifier("gr" + i, "drawable", this.getPackageName()));
^
什么是正确的方法?
Use setBackgroundResource()
使用给定资源 ID 的可绘制(或颜色)资源设置背景。