android - 使用权重属性动态创建复选框
问题描述
我想用 for 循环在 java 中创建复选框。我想将它添加到网格布局中。我的问题是复选框只需要包装内容大小。我希望它们应该覆盖整个宽度。我可以像这样轻松地在 xml 中获取它。
<GridLayout
android:id="@+id/checkBoxLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:columnCount="2">
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
</GridLayout>
但我想像这样添加这些
<GridLayout
android:id="@+id/checkBoxLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:columnCount="2">
</GridLayout>
和Java代码
for (int i = 0; i < 3; i++) {
CheckBox cb = new CheckBox(getActivity());
cb.setText("I'm dynamic!");
cb.setTextColor(Color.WHITE);
cb.setPadding(10, 10, 10, 10);
checkBoxLayout.addView(cb);
}
解决方案
就像是:
final int h = 25;
final int w = 200;
final int margin = 10;
checkBoxLayout.setColumnCount(3);
checkBoxLayout.setRowCount(1);
for( i = 0 ; i < 3 ; i++ ) {
CheckBox check = new CheckBox( getActivity() );
check.setText("Checkout");
// check.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// left, top, right, bottom
params.setMargins(0, margin , 0, margin);
params.gravity = Gravity.NO_GRAVITY;
check.setLayoutParams(params);
check.setGravity(Gravity.CENTER);
checkBoxLayout.addView(check, w, h);
}
推荐阅读
- azure - 计时器触发器 Azure 功能停止工作,没有任何更改
- java - 无法从 EditText 获取文本
- c# - 如何使用 WebRequest C# 在没有 ssl 验证的情况下发送请求?
- python - 我如何在其他功能中使用 get_queryset()object 'list_object'
- sql - 检测包含除“,”和“\ n”以外的特殊字符的列 - Postgresql
- java - Docker 在 IntelliJ 项目设置中找不到我的 .java 文件
- scala - 如何在 Gatling 资源方法中的请求之间传递值?
- amazon-web-services - 在 AWS Secret Manager 和 Active Directory 之间同步密码
- python - 如何使用 `np.choose` 或 `np.take` 或类似方法在 numpy 中对它进行矢量化?
- sql - 检索新值时触发器在 PLSQL 中不起作用