我想在for循环中用java创建复选框。我想在gridlayout中添加它。 我的问题是复选框只包装内容大小。我希望他们应该覆盖全宽。 我可以很容易地在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);
}
答案 0 :(得分:2)
类似的东西:
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);
}
答案 1 :(得分:0)
GridLayout.LayoutParams param = new GridLayout.LayoutParams(GridLayout.spec(
GridLayout.UNDEFINED, GridLayout.FILL, 1f),
GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f));
cb.setLayoutParams(param);