【问题标题】:GridLayout attach an ImageView dynamicallyGridLayout 动态附加一个 ImageView
【发布时间】:2016-09-19 13:02:42
【问题描述】:

我正在尝试使用 GridLayout 创建一个 15(宽度)x20(高度)“方格纸”的视图,就像在 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

【问题讨论】:

    标签: android android-gridlayout


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2013-02-09
      • 1970-01-01
      • 2012-02-06
      • 2015-07-10
      相关资源
      最近更新 更多