android - 如何在 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;
}
解决方案
添加视图时,需要使用 2 参数addView(View, LayoutParameters)
版本添加它。否则你不会得到你刚刚设置的参数,你会得到一个新的参数对象。此外,您需要在循环内移动 params 对象的创建,每个对象都应该有自己的,或者如果您更改它,您会得到奇怪的结果(它们都会改变)。
当然,您可能应该将 GridLayout 或 RecyclerView 与 GridLayoutManager 一起使用,而不是一个一个地添加视图,特别是如果您有超过六个左右的视图。
推荐阅读
- vb.net-2010 - 找不到中间过滤器的组合来建立连接
- android - 从 Fragments 中的 URL 读取数据
- node.js - 云函数因“错误:无法确定 Firebase 数据库 URL”而崩溃。
- javascript - laravel5.8 如何用纯javascript为每个项目打开一个模态窗口
- java - 我该如何解决 - 无法下载 mysql 连接器 .jar... 收到致命警报:protocol_version?
- javascript - 如何等待异步函数导致nodejs
- api-platform.com - 如何使 API-Platform Admin 仅对管理员用户可用?
- c# - 当 RowHeadersVisible = false 时,Datagrid 中的 Visual DataGridBoolColumn 错误
- java - 每次在方法中运行新值
- vue.js - 无法在 vue.js v3 上导入包 aws-sdk