通过ID或代码查找按钮 [英] find button by ID or TAG
问题描述
我创建了一个按钮编程,并给它一个ID和标签。
I created a button programmatically and give it a ID and a Tag.
Button button = new Button(this);
button.setId(i);
button.setTag(anotherID);
我是一个计数器。
i is a counter.
现在我想改变这个按钮的背景,但我不能找到它。
Now i want to change the background of this button, but i can't find it with
findViewByID(ID)
或
findViewWithTag(anotherID)
我使用的ID和anotherID,我创建了按钮的值,但我只得到NullPointerException异常。我没有得到任何IDS从一个XML文件,因为我编程方式创建的按钮。有没有人知道我可以处理这个问题?
I use for ID and anotherID the values that i created the buttons with, but i only get NullPointerExceptions. I get no ids from a XML file, because i create the buttons programmatically. Did anybody know how i can handle this?
推荐答案
您创建的元素保存到像这样的列表
save your created element into a list like this
List<Button> buttons = new ArrayList<Button>();
添加创建按钮,列表
add your created button to the list
Button button = new Button(this);
button.setId(i);
button.setTag(anotherID);
buttons.add(button);
现在你可以在列表像这样
now you can get your created views over the list like this
for(Button b: buttons) {
if(b.getId().equals(your_id_to_check)) {
//DO WHAT YOU WANT
}
}
这篇关于通过ID或代码查找按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!