使用权重属性动态创建复选框

Create checkbox dynamically with weight attribute

我想在 java 中使用 for 循环创建复选框。我想将它添加到 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);
    }

类似于:

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