1

In a for loop I am placing buttons on the screen and setting their id as

   LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
    layout.setOrientation(LinearLayout.VERTICAL);
    Button btn = null;
    for (int i = 0; i < buttons_in_row; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        for (int j = 0; j < buttons_in_row; j++) {
            btn = new Button(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
            params.setMargins(5, 5, 5, 5);
            btn.setLayoutParams(params);
            btn.setText("B " + (j + 1 + (i * buttons_in_row)));
            btn.setId(j + 1 + (i * buttons_in_row));
            btn.setWidth(width / buttons_in_row);
            btn.setHeight(width / buttons_in_row);
            btn.setBackgroundResource(R.drawable.button);
            GradientDrawable drawable = (GradientDrawable) btn.getBackground();
            drawable.setColor(Color.parseColor("#" + colors[random_color][0]));
            btn.setOnClickListener(this);
            //Log.i("btn.getsize", btn.getWidth() + ", " + btn.getHeight());
            row.addView(btn);
        }


        layout.addView(row);
    }
    Button b = (Button) layout.findViewById(2);

At the end of the loop I want to pick one of the buttons (e.g. No.2) and give it a different background color.

I tried these

Button b = (Button) findViewById(2);
btn.getId(2);

How can I do that?

erdomester
  • 11,789
  • 32
  • 132
  • 234

3 Answers3

0

You must be adding these buttons to a view (RelativeLayout or LinearLayout etc); you can access buttons via that layout.

For Example you must be doing something like this:

LinearLayout myLayout = (LinearLayout) findViewById(R.id.linear_layout_tags);

        for (int i = 0; i < 3; i++) {

            for (int j = 0; j < 4; j++) {
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                btnTag.setText("Button " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                myLayout.addView(btnTag);
            }
        }

Here, considering the example, you can find button by its id like this:

Button b = (Button) myLayout.findViewById(WHAT_EVER_ID_I_SET_IN_LOOP);

Update

In Android Studio click on light bulb on line with this 'error'. And select Disable inspection in first submenu.

Most probably, Id's created in this way will not create problem but there are other ways to create id's see following link.

How can I assign an ID to a view programmatically?

Community
  • 1
  • 1
  • I do the same, I added my code to the question. On `Button b = (Button) row.findViewById(2);` I get the error `Expected resource of type id` – erdomester Sep 26 '15 at 09:17
  • In Android Studio click on light bulb on line with this 'error'. And select Disable inspection in first submenu. –  Sep 26 '15 at 09:23
  • You're right, this is just a warning, not an error, but can I be sure that this won't throw errors on other devices/os versions? – erdomester Sep 26 '15 at 10:43
  • There are other ways to create id's, but you have to change little bit of your code (in loop), see my updated answer, I have provide ref to another similar question –  Sep 26 '15 at 11:13
0

You can create your own button object as;

public class MyButton {

    private int id;
    private Button button;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Button getButton() {
        return button;
    }

    public void setButton(Button button) {
        this.button = button;
    }
}

Then, you can create an Arraylist and set them ids as you did in the loop. Create an another loop to find;

public static Button findMyButton(int id) {
    for (MyButton myButton: myButtonList) {
        if (myButton.getId() == id)
            return myButton
    }
    return null;
}

When you set your button id manually, it may be duplicated with "auto generated id of any view from android".

Sedat Polat
  • 1,631
  • 2
  • 18
  • 28
0

You can identify your views by two ways..

  • byId
  • byTag.

If you want to set Id to your views programmatically.. you need to set like this..

masterLayout.setId(R.id.masterLayout);

where R.id.masterLayout is from ids.xml which is inside values folder

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="masterLayout" type="id">masterLayout</item>
</resources>

other ways is to identify view is "byTag".

Button button = new Button(this);
button.setText("Button "+i);
button.setTag(i);
button.setOnClickListener(this);
masterLayout.addView(button);

to get this view..

@Override
public void onClick(View view) {
    switch((Integer)view.getTag()){
        case 0:
            Toast.makeText(this, "Clicked Button 0", Toast.LENGTH_SHORT).show();
            break;
        case 1:
            Toast.makeText(this, "Clicked Button 1", Toast.LENGTH_SHORT).show();
            break;
    }
}

before all these.. you need to add your view to a layout.

Full implementation is explained here..

public class DynamicViewActivity extends Activity implements View.OnClickListener{
      private LinearLayout mLayout;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_dynamic_views);
            mLayout = (LinearLayout) findViewById(R.id.mLayout);
            createDynamicViews();
      }

      private void createDynamicViews() {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                    , LinearLayout.LayoutParams.MATCH_PARENT);
            ScrollView scrollView = new ScrollView(this);
            scrollView.setLayoutParams(layoutParams);

            LinearLayout masterLayout = new LinearLayout(this);
            masterLayout.setId(R.id.masterLayout);
            masterLayout.setLayoutParams(layoutParams);
            masterLayout.setOrientation(LinearLayout.VERTICAL);
            scrollView.addView(masterLayout);

            for(int i = 0; i < 2; i++){
                Button button = new Button(this);
                button.setText("Button "+i);
                button.setTag(i);
                button.setOnClickListener(this);
                masterLayout.addView(button);
            }

            mLayout.addView(scrollView);
      }

      @Override
      public void onClick(View view) {
            switch((Integer)view.getTag()){
                case 0:
                    Toast.makeText(this, "Clicked Button 0", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(this, "Clicked Button 1", Toast.LENGTH_SHORT).show();
                    break;
            }
      }
}
SureshCS50
  • 3,608
  • 1
  • 20
  • 27