Mreza Nemati
Mreza Nemati

Reputation: 74

how accessing similar name variables in java

i have 5 button as btn1, btn2, btn3, btn4, btn5 and a integer variable as numberInt

i want when numberInt changed to a number, button with that number becomes invisible like this:

if (number == 1){
   btn1.setVisibility(View.GONE);
}else if (number == 2){
   btn2.setVisibility(View.GONE);

is there any way to use numberInt end of 'btn' keyword? because is hard to write if loops when buttons is too many.

Sorry for bad explaining.

Upvotes: 0

Views: 71

Answers (2)

jsp phani
jsp phani

Reputation: 38

You need not use 'If loop' if all your buttons are put in an array. Since arrays have 'int' as index that can be used to your advantage.

Button[] buttons = {btn0, btn1, btn2, ...};

use a method as below to update view's visibility

public void setInvisibleButton(int i){
   buttons[i].setVisibility(View.GONE)
}

Upvotes: 0

Michael
Michael

Reputation: 44100

Put all the buttons in a list

List<Button> buttons = new ArrayList();
buttons.add(btn1);
buttons.add(btn2);

then refer to them by index

buttons.get(number);

There is no way to construct an identifier at runtime e.g.

btn${number}.setVisibility(View.GONE); // not valid java

You can do that kind of thing in some scripting languages, but not in Java.

Upvotes: 4

Related Questions