![](/img/trans.png)
[英]Android is not matching closest size drawable when I use getResources().getIdentifier()
[英]Obtain a drawable with getResources().getIdentifier() in android
我想以編程方式調整按鈕數組中幾個按鈕的背景。 在這樣做時,我想從一個字符串和一個數字組合標識符。
對於strings.xml
中的文本資源,我已經能夠在功能上將其組合在一起:
basicDEGR[g].setVoc(getResources().getIdentifier("vocGR" + (g +((category-1)*20)), "string", getPackageName()));
不幸的是,與drawables類似的方法不起作用:
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()));
^
什么是正確的方法?
使用setBackgroundResource()
使用給定資源 ID 的可繪制(或顏色)資源設置背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.