Ad

How Can I Modify Object Name In A Loop

- 1 answer

I have a code like below. Now I want to use loop and I need to modify object's name for that purpose. I need something like addView(toString(txt+"i")) for i = 1,2 in my loop to get "txt2" and to be able to iterate.

But this doesn't work. What will work?

public void click2(View view) {
    Button button3 = findViewById(R.id.button2);
    button3.setText("hello");

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
    Button txt1 = new Button(this);
    // linearLayout.setBackgroundColor(Color.TRANSPARENT);
    linearLayout.addView(txt1);

    Button txt2 = new Button(this);
    // linearLayout.setBackgroundColor(Color.TRANSPARENT);
    linearLayout.addView(txt2);
}
Ad

Answer

You can't get local variables using their names (identifiers) at runtime. However, one solution is to use an array instead to hold the buttons.

public void click2(View view) {
    Button button3 = findViewById(R.id.button2);
    button3.setText("hello");

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);

    // Put buttons into an array
    Button[] txt = {new Button(this), new Button(this)};
    
    // loop over all values of i between 0 to the end of the button array
    for (int i = 0; i < txt.length; i = i + 1) {
        // Access array elements by index so txt1 is txt[1], etc.
        linearLayout.addView(txt[i]);
    }
}

But if you only have 3 or so buttons with distinct purposes it would probably be better to leave it as is.

Ad
source: stackoverflow.com
Ad