【问题标题】:GridLayout or GridView better to reference static items?GridLayout 或 GridView 更好地引用静态项?
【发布时间】:2015-08-02 09:03:11
【问题描述】:

我正在构建一个简单的 Whack a Mole 克隆,但我无法弄清楚如何进行布局。我没有玩过Android dev,因为Gingerbread 是新的,而且我以前从未尝试过写游戏,所以如果这些是新手问题,请原谅我,但我已经被困在谷歌上几个小时了,我我没有得到答案。

我基本上有一个3x4GridLayout,在layout.xml 文件中声明了12 隐形痣ImageView,我无法弄清楚如何在我的代码中创建对象引用根据我在 XML 中创建的内容,我可以让它们随机出现和消失并处理用户触摸事件。

我看到了很多关于 GridViewsAdapter 对象的信息,这些对象用于从 xml 创建引用并处理触摸事件,但我不确定如何使用 GridLayout 执行此操作。我应该切换到在LinearLayout 中使用GridView,还是缺少一些非常简单的东西?

另外,在我的Activity 子类或View 子类中实现onItemClickedListener() 会更好吗?我对我的 View 子类与 XML 布局的关系感到有些困惑。也许我只是过于复杂了?

感谢您的帮助,伙计们。如果有帮助,这是我的 layout.xml。

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="4"
android:useDefaultMargins="true"
android:background="@drawable/grass_bg"
android:id="@+id/wam_view_layout">
<ImageView
    android:id="@+id/mole1"
    android:visibility="invisible"
    android:layout_width="120dip"
    android:layout_height="140dip"
    android:contentDescription="@string/mole_description"
    android:layout_gravity="center"
    android:scaleType="fitCenter"
    android:src="@drawable/mole" />
<ImageView
    android:id="@+id/mole2"
    android:visibility="invisible"
    android:layout_width="120dip"
    android:layout_height="140dip"
    android:contentDescription="@string/mole_description"
    android:layout_gravity="center"
    android:scaleType="fitCenter"
    android:src="@drawable/mole" />

<!--pattern continues until mole12-->

</GridLayout>

【问题讨论】:

  • 添加您的布局 XML。您付出的一些代码,例如使用GridView

标签: android xml gridview layout


【解决方案1】:

在你的活动中做类似的事情:

private ImageView imageMole1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout);

    imageMole1 = (ImageView) findViewById(R.id.mole1);
    imageMole1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // handle click here e.g. call a method
            // void onMoleClicked(int moleId)
        }
    });
}

要更改显示的图像,请使用例如:

imageMole1.setImageResource(R.drawable.mole_gone);

【讨论】:

  • 谢谢!所以我什至根本不需要创建适配器子类?
  • 你可以使用它,但我想在你的情况下它并不是真的必要。 GridView 对于大量项目具有更好的性能。此外,您只需要一键式侦听器即可查看网格视图。此外,如果你有一个合适的模型,网格视图适配器可以很容易地让你的视图保持更新。所以这取决于你和你的编程技能......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多