Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 965
Zar E Ahmer Avatar asked Aug 12 '14 07:08

Zar E Ahmer


2 Answers

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());
}
like image 108
Giru Bhai Avatar answered Oct 15 '22 10:10

Giru Bhai


If you already know all the ids, you can simply use:

int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];

for(int i=0 ; i < arrayButton.length ; i++)
{
  arrayButton[i] = (Button) findViewById(ids[i]);
}

Or if you don't know them, use:

getResources().getIdentifier("btn1","id",getPackageName())
like image 44
Simon Marquis Avatar answered Oct 15 '22 10:10

Simon Marquis