How do I programmatically add buttons into layout one by one in several lines?

The issue is that your buttons are not going to automatically wrap to the next part of the screen. You have to specifically tell Android how you want your Views to be positioned. You do this using ViewGroups such as LinearLayout or RelativeLayout.

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

        for (int i = 0; i < 3; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        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));
            row.addView(btnTag);
        }

        layout.addView(row);
    }

I’m assuming that R.id.linear_layout_tags is the parent LinearLayout of your XML for this activity.

Basically what you’re doing here is you’re creating a LinearLayout that will be a row to hold your four buttons. Then the buttons are added and are each assigned a number incrementally as their id. Once all of the buttons are added, the row is added to your activity’s layout. Then it repeats. This is just some pseudo code but it will probably work.

Oh and next time be sure to spend more time on your question…

https://stackoverflow.com/questions/how-to-ask

Leave a Comment