1

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?

2 Answers 2

5

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);     
}
Sign up to request clarification or add additional context in comments.

2 Comments

oh yes a button array!However, if I want to set the order of the button according to the string values(which the string values will change), is there a way to do this?
@user3947486 Yes. An arraylist is waiting for you :)
1

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);
    }
    

1 Comment

Eclipse said getResources cannot be resolved. I have tried to import but there is no import available. What should I do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.