androidviewandroid-resourcesr.java-fileandroid-identifiers

Get View ids in a for loop programatically?


I simply want to know . is there a way to create an id's using for loop

I have 10 buttons in xml . there id's are button1,button2,button3... button10 Now i create an Array of Button in java class and do it like this

public class Menu extends Activity
{
    Button[] arrayButton=new Button[10];

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        init();
    }

    private void init()
    {
        for(int i=1 ; i<9 ; i++)
        {
            String abc = "but"+String.valueof(i);
            int x = Integer.parseInt(abc);


            Log.d("abc", abc);

            Log.d("x", String.valueOf(x) );

            //arrayButton[i] = (Button) findViewById(R.id.x);  // giving error 

            //arrayButton[i].setText("Hello:");
        }
    }

}

I want to know how can i do this kind of work . Getting all button using for loop to make my work faster and some time when i want to set the text of all the buttons .


Solution

  • use getResources().getIdentifier like

    String abc = "but"+String.valueof(i);
    int resID = getResources().getIdentifier(abc, "id", getPackageName());
    arrayButton[i] = (Button) findViewById(resID );
    arrayButton[i].setText("Hello:");
    

    i.e. simply rewrite init() method as

    private void init()
        {
            for(int i=1 ; i<9 ; i++)
            {
                String abc = "but"+String.valueof(i);
                int resID = getResources().getIdentifier(abc, "id", getPackageName());
                arrayButton[i] = (Button) findViewById(resID);
                arrayButton[i].setText("Hello:");
            }
        }
    

    Or simple you may use

        int[] buttonIDs = new int[] {R.id.but1, R.id.but2, R.id.but3,R.id.but4, ... }
        for(int i=0; i<buttonIDs.length; i++) {
            Button b = (Button) findViewById(buttonIDs[i]);
            b.setText("Hello:" + b.getText().toString());
    }