首页 > 解决方案 > 如何在 Android 中以编程方式设置按钮的边距?

问题描述

我以编程方式在 GridLayout 中添加了 50 多个按钮,其中包含 ScrollView 和 LinearLayout 作为 GridLayout 父级。我需要为每个按钮设置边距。我尝试了 setMargins() 方法。但是,它不起作用。谁能帮帮我吗?

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>

创建按钮的代码。

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;
    }

标签: android

解决方案


添加视图时,需要使用 2 参数addView(View, LayoutParameters)版本添加它。否则你不会得到你刚刚设置的参数,你会得到一个新的参数对象。此外,您需要在循环内移动 params 对象的创建,每个对象都应该有自己的,或者如果您更改它,您会得到奇怪的结果(它们都会改变)。

当然,您可能应该将 GridLayout 或 RecyclerView 与 GridLayoutManager 一起使用,而不是一个一个地添加视图,特别是如果您有超过六个左右的视图。


推荐阅读