good_evening
good_evening

Reputation: 21749

Can I add array to android buttons?

My button is:

  <Button
      android:text=""
      android:id="@+id/b1"
      android:gravity="center_horizontal"
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:background="@drawable/the_border"
      android:textSize="75sp"/>

And I have many of them (b0, b1, b2)...

My java:

    for(int index = 0; index < 9; index++)
    {
        places[index] = (Button) findViewById(R.id.b + index);
        places[index].setOnClickListener(this);
    }

How could I do this? findViewById(R.id.b + index) needs to be changed. Is it possible? Thanks

Upvotes: 0

Views: 133

Answers (2)

StErMi
StErMi

Reputation: 5469

In that way you are not adding that buttons at the layout.

1) you cannot give to those buttons (or container/element in general) the same ID. An id is an unique identifier so it has to be unique 2) findViewById will search into the layout three to find an element with that id. If that element don't exist (you are not adding them to the layout) it will fail with a nullpointerexception.

What you have to do is to create Buttons from your java code and add them to a container (for example a LinearLayout).

So you do a findViewById and look for the container, then you add View (the button) to that container.

Do you need a code example?

Upvotes: 0

Seva Alekseyev
Seva Alekseyev

Reputation: 61351

Use the tag property to give them sequential tags of 0, 1, 2, etc., then findViewWithTag() in a loop to build an array. Note that tag is a string, it's not numeric.

Upvotes: 1

Related Questions