gpt4 book ai didi

android - 按 ID 或 TAG 查找按钮

转载 作者:太空狗 更新时间:2023-10-29 16:22:57 25 4
gpt4 key购买 nike

我以编程方式创建了一个按钮并为其指定了一个 ID 和一个标签。

Button button = new Button(this);
button.setId(i);
button.setTag(anotherID);

我是一个计数器。

现在我想改变这个按钮的背景,但是我找不到

findViewByID(ID)

findViewWithTag(anotherID)

我将创建按钮时所用的值用于 ID 和 anotherID,但我只得到 NullPointerExceptions。我没有从 XML 文件中获取任何 ID,因为我以编程方式创建按钮。有人知道我该如何处理吗?

最佳答案

将您创建的元素保存到这样的列表中

List<Button> buttons = new ArrayList<Button>();

将您创建的按钮添加到列表中

Button button = new Button(this);
button.setId(i);
button.setTag(anotherID);

buttons.add(button);

现在您可以像这样在列表中创建 View

for(Button b: buttons) {
if(b.getId().equals(your_id_to_check)) {
//DO WHAT YOU WANT
}
}

关于android - 按 ID 或 TAG 查找按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9783102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com