0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.