Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I modify object name in a loop

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading