user3947486
user3947486

Reputation: 25

How to get a button by variable name using a string?

My code is like this...

public class MainActivity extends Activity {
    String a = new String("1,2,3,4,5")

    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Button button5;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startBtn = (Button) findViewById(R.id.startBtn);

        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                String[] splited=a.split(",");
                for(String b : splited){
                    (button"b").setBackground(Color.RED); 
                   //This is the part where I get stucked//
                    //I know the code is wrong but I just want to express my idea//
                }
            }
        });
    }
}

So,how can I name the button with a changing String b?

The button1 should changing its background color first, then button2, button3, and so on.

Any ideas?

Upvotes: 1

Views: 1175

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122026

No, That is not the way. You cannot do that for a variable name (unless you use reflection). Instead of that string take a Button array.

private Button[] buttons = {button1,button2.....};

Later

for(Button b : buttons ){
    b.setBackground(Color.RED);     
}

Upvotes: 5

0101100101
0101100101

Reputation: 5911

There's only two ways:

  1. What Suresh Atta mentioned, because it's not possible to access variable names without reflection.

  2. Accessing the button resources like this (given the IDs of the buttons in XML are button1, button2 and so on):

    for (String b : splited){
        findViewById(getResources().getIdentifier("button" + b, "id", getPackageName()))
            .setBackgroundColor(Color.RED);
    }
    

Upvotes: 1

Related Questions