Android 从代码填充GridLayout不需要';不能给出与XML相同的结果
我尝试在代码中复制以下XML:Android 从代码填充GridLayout不需要';不能给出与XML相同的结果,android,grid-layout,cardview,Android,Grid Layout,Cardview,我尝试在代码中复制以下XML: <GridLayout android:id="@+id/row2Grid" android:layout_row="1" android:layout_column="0" android:layout_rowWeight="40" android:layout_width="match_parent" android:layout_height="wrap_content" android:al
<GridLayout
android:id="@+id/row2Grid"
android:layout_row="1"
android:layout_column="0"
android:layout_rowWeight="40"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alignmentMode="alignMargins"
android:columnCount="3"
android:columnOrderPreserved="true"
android:padding="0px"
android:rowCount="2"
>
<!-- Box 1 -->
<androidx.cardview.widget.CardView
app:cardBackgroundColor="#00ff00"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="8"
android:layout_column="0"
android:layout_columnWeight="6"
android:layout_marginRight="3dp"
android:layout_marginBottom="3dp">
</androidx.cardview.widget.CardView>
<!-- Box 2 -->
<androidx.cardview.widget.CardView
app:cardBackgroundColor="#ff0000"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_rowWeight="8"
android:layout_column="1"
android:layout_columnWeight="6"
android:layout_marginRight="3dp"
android:layout_marginBottom="3dp"
app:cardElevation="8dp">
</androidx.cardview.widget.CardView>
</GridLayout>
但它不起作用,只产生以下结果:
我做错了什么?你知道,当你为一个问题挣扎了几个小时,然后你一问这个问题,你就看到了自己的解决方案 我一贴出问题就看到了答案。这当然是由于我首先这样做:
GridLayout.LayoutParams cardViewLayoutParams = new GridLayout.LayoutParams(GridLayout.spec(0), GridLayout.spec(row2children));
cardViewLayoutParams.columnSpec = GridLayout.spec(0,8.0f);
cardViewLayoutParams.rowSpec = GridLayout.spec(0,8.0f);
当我创建cardViewLayoutParams
时,我在构造函数中指定cardView的行和列属性,但在其正下方覆盖它们。将此更改为以下内容:
GridLayout.LayoutParams cardViewLayoutParams = new GridLayout.LayoutParams();
cardViewLayoutParams.columnSpec = GridLayout.spec(row2children,8.0f);
cardViewLayoutParams.rowSpec = GridLayout.spec(0,8.0f);
让一切都按预期进行
GridLayout.LayoutParams cardViewLayoutParams = new GridLayout.LayoutParams();
cardViewLayoutParams.columnSpec = GridLayout.spec(row2children,8.0f);
cardViewLayoutParams.rowSpec = GridLayout.spec(0,8.0f);