2010-11-07 68 views
5

我有個問題讓我發瘋。動態訪問佈局元素

我的屏幕上有很多按鈕(10或更多或更少),在TableRow中。

我需要訪問它們,並且我計劃通過循環執行。

訪問之一,是很容易的,添加此:

boton7 = (Button) findViewById (R.id.Btn7) 

我的問題是,如果你能動態設置ID字符串(R.id.Btn7)放在一個可以得到的按鈕,例如,改變顏色....是這樣的:

for (int i = 0; i <10; i + +) { 
    Button eachBoton= (Button) findViewById (R.id.Btn + i); 
    eachBoton. setBackgroundColor (Color.Red); 
} 

那當然,不工作....我的問題是,如果有人知道鏈究竟如何可以安裝

R.id.Btn + i 

工作。

非常感謝。

回答

13

您可以使用Ressources::getIdentifier()來獲取資源標識符爲給定的資源名稱:

int ressourceId = getResources().getIdentifier(
    "Btn"+i, 
    "id", 
    this.getContext().getPackageName()); 
Button button = (Button) findViewById(ressourceId); 

或者你可以用你需要的所有ID和數組元素的訪問準備的數組。這是更有效的:

private final int[] btns = {R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, ...} 
... 
Button button = (Button) findViewById(btns[i]); 
+0

感謝回答。我使用這個並且工作! – 2010-11-07 14:17:59

+0

謝謝,我發現這對於動態加載資源非常有用。 – 2011-05-04 22:17:05

2

(在下面的例子中「佈局」)給出的標識符佈局,然後通過使用getTouchables遍歷所有可接觸的孩子。如果它是一個按鈕,請更改顏色。

View layout = findViewById(R.id.layout) 
ArrayList<View> touchables = layout.getTouchables(); 
for (View b : touchables) { 
    if (b instanceof Button) { 
     b.setBackgroundColor(Color.Red); 
    } 
}