0
votes

I have Programmatically added more than 50 buttons in a GridLayout which contains ScrollView and LinearLayout as GridLayout Parents. I need to set margins for every button. I tried setMargins() method. But, it doesn't work. Can anyone Please help me?

XML

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_marginBottom="10dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">

            <GridLayout
                android:id="@+id/levelsGridLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:columnCount="5"
                android:rowCount="10">


            </GridLayout>

        </ScrollView>

    </LinearLayout>

Code to create Buttons.

FrameLayout.LayoutParams params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
    );
    for (int i = 1; i <= 100; i++) {
        Button button = new Button(this);
        button.setText(Integer.toString(i));
        id = getResources().getIdentifier("button" + i, "id", getPackageName());
        button.setId(id);
        button.setTag(Integer.toString(i));
        button.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        button.setTextColor(Color.WHITE);
        button.setBackgroundResource(R.drawable.levels_button_background);
        params.setMargins(5, 5, 5, 5);
        button.setLayoutParams(params);
        allLevelButtons.add(button);
        levelsGridLayout.addView(button);
        button.getLayoutParams().width = oneButtonWidth;
    }
1

1 Answers

0
votes

When you add the view, you need to add it with the 2 parameter addView(View, LayoutParameters) version. Otherwise you don't get the params you just set, you get a new params object. Also, you need to move the creation of the params object inside the loop, each one should get its own, or if you ever change it you'll get weird results (they'd all change).

Of course you should probably be using a GridLayout or RecyclerView with a GridLayoutManager rather than adding views one by one, especially if you have more than half a dozen or so.