Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android iterating through button id's with a for loop in Java

Tags:

java

android

I have a few buttons on an activity for an app I am working on.

I have the text for each stored in an array (the data can change) and I am trying to update all of them with a for loop.

The Id's are button1, button2, and button3

This is 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]);
    }
like image 544
Josh Young Avatar asked Sep 11 '15 03:09

Josh Young


1 Answers

As a simple solution you should try iterating over the containing view's children:

Considering you have your buttons all inside a Layout like this:

<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 just simple iterate over 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]);
    }

}

A better approach, however, would be to create the buttons dynamically based on your array size and adding them to LinearLayout instead of copy/pasting them inside your layout.xml file. This would help you to have the exact number of buttons per each value on your array every time you may want to add/remove something to 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
}
like image 134
Rob Avatar answered Sep 17 '22 18:09

Rob