通过ID或标签查找按钮

问题描述:

我通过编程创建了一个按钮并为其提供了一个ID和一个标签。通过ID或标签查找按钮

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

我是一个柜台。

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

findViewByID(ID) 

findViewWithTag(anotherID) 

我使用的ID找到它,anotherID我创建的值按钮,但我只能得到NullPointerExceptions。我没有从XML文件中获得ID,因为我以编程方式创建按钮。有没有人知道我该如何处理?

+0

请把错误日志在这里 – 2012-03-20 09:48:27

+0

我认为'yourview'你添加按钮,那么你应该调用'yourview.findViewByID(id)'来找到它。 – dreamtale 2012-03-20 10:11:20

保存您创建的元素放入一个列表这样

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

添加创建按钮,列表

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

buttons.add(button); 

现在你可以在列表中选择您创建的视图这样

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

我试试这个解决方案,它从我的作品 – 2012-03-20 12:11:46

+1

非常有帮助。谢谢 – YeeKhin 2015-07-16 18:00:47

您通常会保持对您的程序创建按钮的引用。切勿手动设置ID。 R文件是在编译时创建的,而不是运行时,所以你的尝试是错误的。

使用标签查找控件的ID,我粘贴代码here..may这对你有帮助。

Button button = new Button(this); 
button.setTag(value); 

int Qid = button.getTag(); 
+0

这是我也尝试,但我有问题再次找到标签,findViewWithTag(anotherID)是我尝试,但我没有得到它的工作 – 2012-03-20 10:43:32

首先你想做什么?如果您想在动态创建背景色后更改Button背景色,那么您的代码很好,但不要给它ID。由于id是由文件R.java生成的整数值。

只是看到它,你会知道:

因此,使用下面的代码:

Button button = new Button(this); 
button.setBackgroundColor(Color.White); 

希望你得到了点。如果您有任何问题,请告诉我。

+0

是的,我想改变按钮的颜色后,我创建它。我得到了20个按钮,并获得了“状态”。我想改变其中一些事件的状态。 – 2012-03-20 10:41:07

+0

你想改变哪种状态? – 2012-03-20 10:51:53

+0

你是如何得到这个状态的?或者你可以定义每个按钮不同的名称,并能够改变背景颜色 – 2012-03-20 10:52:41

这是我Soulution:

public static List<Button> buttons = new ArrayList<Button>(); 
public static List<Integer> ids = new ArrayList<Integer>(); 

...

buttons.add(button); 
ids.add(something.getInt(0)); 

...

public void changeButtonState(int res, int ID){ 
    int counter = 0; 
    for(Integer i: ids){ 
     if(i==ID){ 
      Button b = buttons.get(counter); 
      b.setBackgroundResource(res); 
     } 
     counter++; 
    } 
} 

它的工作原理非常适合我的情况。这些ID是数据库中的一些ID,它们没有排序。