How to associate a variable to an ID?

Asked

Viewed 109 times

0

I have an integer array and need to associate this value to a given button, to change its backgound. If the array has the number "40", I need the "button40" to change color. and so on, until the whole array is checked. Basically, what I need is to associate a variable with an ID.

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

2 answers

2


There are a few options. What I 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();
}

1

Having the Id of a View is possible to obtain the reference to it using the method findViewById() the layout containing it.

So, if the values that are in the array correspond to the Ids declared in xml, it is easy to match these 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.