How to associate a variable with an ID?

0

I have an array integer and I need to associate this value with a certain button, to change its backgound. if there is a "40" in the array, I need the "40" button to change color. and so on until the entire array is checked. Basically, what I need is to associate a variable with an ID.

Type: Button (X) .setBackgroundColor (Color.BLUE); Being X an INT variable

    
asked by anonymous 02.12.2016 / 11:20

2 answers

2

You have a few options. The one I would advise would be to use a simple HashMap.

Map<Integer, Button> buttonsHash = new HashMap<Integer, Button>();

public Button getButton(int position){
    return buttonsHash.get(position);
}

public void addButton(int position, Button button){
    buttonsHash.put(position, button);
}

public void changeButtonColor(int position, int color){
    Button button = getButton(position);
    if(button != null) button.setBackgroundColor(color);
    else throw new NullPointerException();
}
    
02.12.2016 / 11:34
1

Having the ID of a View is possible to get the reference to it using the findViewById () of the layout that contains it.

So, if the values that are in the array match the declared Ids in xml, it's easy to match those values to the buttons.

int[] arrayButtons = new int[]
    {
         R.id.Button00,
         R.id.Button01,
         R.id.Button02,
         R.id.Button03,
         R.id.Button04,
         ...
    }

int idButton04 = arrayButtons[4];
Button button04 = findViewById(idButton04);
button04.setBackgroundColor(Color.BLUE);
    
02.12.2016 / 12:59