2

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)

or

findViewWithTag(anotherID)

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?

Boe-Dev
  • 1,585
  • 2
  • 14
  • 26
  • I think Where the `yourview` you added the button, then you should call `yourview.findViewByID(id)` to find it. – dreamtale Mar 20 '12 at 10:11

5 Answers5

7

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
     }
}
silly
  • 7,789
  • 2
  • 24
  • 37
0

You would normally keep a reference to your programmatically created button. Never set Id manually. the R file is created at compille time not runtime so what your trying is plain wrong.

Warpzit
  • 27,966
  • 19
  • 103
  • 155
0

use tag for find id of controls, i am pasting code here..may this help to you.

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

int Qid = button.getTag();
Hasmukh
  • 4,632
  • 2
  • 30
  • 44
  • This is what i also try, but i got problems to find the Tag again, findViewWithTag(anotherID) is what i try, but i dont get it to work – Boe-Dev Mar 20 '12 at 10:43
0

First of all What you want to do? If you want to change the Button Background color after creating it dynamicaly then your code is fine but don't give ID to it. As because id is the Integer Value Generated by the file R.java.

Just See it and you will come to know:

So use below code:

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

Hope you got the point. If you have any issue then let me know.

Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188
0

This is my 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++;
    }
}

it works perfect for my situation. The ids are some ids from the database, the are not sorted.

Boe-Dev
  • 1,585
  • 2
  • 14
  • 26