2010-11-07 67 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); 
    } 
}