Java – android uses a for loop to traverse button IDs in Java

android uses a for loop to traverse button IDs in Java… here is a solution to the problem.

android uses a for loop to traverse button IDs in Java

I

have several buttons on the Activity of the application I’m developing.

I

store the text of each text in an array (the data can be changed) and I’m trying to update all the text using a for loop.

The IDs are button1, button2, and button3

That’s what I want

for(int i=1; i<=splitter.length; i++){
        Button button = (Button)findViewById(R.id.button[i]);//<---How do i make this work

button.setText(spliter[i-1]);
    }

Solution

As a simple solution, you should try iterating over a subview that contains a View:

Considering that all your buttons are in such a layout:

<LinearLayout
    android:id="@+id/layout_container_buttons"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Button1"/>

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Button2"/>

</LinearLayout>

Then simply iterate through all the layout children:

ViewGroup layout = (ViewGroup)findViewById(R.id.layout_container_buttons);
for (int i = 0; i < layout.getChildCount(); i++) {

View child = layout.getChildAt(i);
    if(child instanceof Button)
    {
        Button button = (Button) child;
        button.setText(spliter[i]);
    }

}

However, a better approach is to dynamically create buttons based on your array size and add them to LinearLayout instead of copy/paste them into your layout.xml file. This will help you get the exact number of buttons for each value in the array every time you might want to add/remove something from it.

ViewGroup layout = (ViewGroup) findViewById(R.id.layout_container_buttons);
for (int i = 0; i < splitter.length; i++) // iterate over your array
{
     Create the button
    Button button = new Button(this);
    button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                         LinearLayout.LayoutParams.WRAP_CONTENT));
    button.setText(splitter[i]);
    layout.addView(button);  add to layout
}

Related Problems and Solutions