GridLayout动态附加ImageView

时间:2016-09-19 04:51:47

标签: android android-gridlayout

我正在尝试创建一个15(宽)x20(高)和#34;图纸"比如在GridLayout上使用xml定义的视图。

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:columnCount="15"
                    android:orientation="vertical"
                    android:rowCount="20"
                    android:layout_margin="2dp"
                    android:id="@+id/gridLayout_mazeLayout">
                    <View
                        android:layout_width="15dp"
                        android:layout_height="15dp"
                        android:layout_row="0"
                        android:layout_column="0"
                        android:background="#51ffff"
                        android:layout_margin="1dp"/>
                    <View
                        android:layout_width="15dp"
                        android:layout_height="15dp"
                        android:layout_row="0"
                        android:layout_column="1"
                        android:background="#51ffff"
                        android:layout_margin="1dp"/>
                    <View
                        android:layout_width="15dp"
                        android:layout_height="15dp"
                        android:layout_row="0"
                        android:layout_column="2"
                        android:background="#51ffff"
                        android:layout_margin="1dp"/>
    // rest of rows and cols not shown.
     </GridLayout>

我想附加ImageView跨越3x3单元格

   gridLayout_mazeLayout = (GridLayout) rootView.findViewById(R.id.gridLayout_mazeLayout);
   ImageView imageView_robot = new ImageView(rootView.getContext());
   imageView_robot.setBackgroundResource(R.mipmap.imageacross3x3);

    GridLayout.Spec row = GridLayout.spec(0);
    GridLayout.Spec col = GridLayout.spec(0);
    GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(row, col);
    gridLayout_mazeLayout.addView(imageView_robot,gridLayoutParam);

但这样做似乎为ImagineView引入了新的空间。我想要实现的是将ImagineView附加在单元格的顶部,而不是将其添加到GridLayout

1 个答案:

答案 0 :(得分:0)

更改<View&gt;在具有唯一ID的<GridLayout><ImageView>内,然后您可以使用findViewById()在Java代码中获取实例,或者如果您想动态构建它,只需从{{1}中删除<View>标记并使用<GridLayout>addView()插入ImageView