gpt4 book ai didi

Android onClickListener 不触发 subview

转载 作者:太空狗 更新时间:2023-10-29 15:11:09 26 4
gpt4 key购买 nike

我正在开发一个使用 onClickListeners 来翻转图 block 的应用程序。我在 RelativeLayout 中拥有全部内容。然后我有第二个 RelativeLayout 来包含我所有的图 block ,以便于清除和添加。我还在 xml 中预定义了各种其他按钮。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/boardlayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/board"
tools:context=".MainActivity" >

<RelativeLayout
android:id="@+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

</RelativeLayout>

<ImageView
android:id="@+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/skill2Button"
android:layout_alignParentRight="true"
android:src="@drawable/ic_menu" />

</RelativeLayout>

在代码中,我添加了 Tiles,它们是具有我的自定义操作的 ImageView。我还向它们添加了 onClickListeners。 grid 变量是我上面显示的 mainlayout RelativeLayout。

private void createTiles(){
//Create the tiles
int j = 0;
Tile t;
for(int i = 0; i < 30; i++){

int r = i/5;
int c = j%5;
t = new Tile(this, r, c);
t.setOnClickListener(tileClicked);

j++;
if(j == 5)
j=0;

grid.addView(t);
}
}

问题在于较旧的 Android 版本,这些图 block 似乎永远不会触发点击事件。我将 onClickListeners 添加到图 block ,然后在 RelativeLayout 上添加一个只是为了测试,RelativeLayout 获取事件,但图 block 没有。

菜单 ImageView(在上面的 xml 中显示)也有一个 onClickListener,它会被触发。

在较新的 Android 版本中,这可以正常工作。这让我想知道旧版本是否存在从代码中添加的 View 传递事件的问题。

有人可以告诉我旧版本做错了什么吗?

最佳答案

试试这个,

private void createTiles(){
//Create the tiles
int j = 0;
Tile t[30];

for(int i = 0; i < 30; i++){

int r = i/5;
int c = j%5;
t = new Tile(this, r, c);
t[i].setOnClickListener(this);

j++;
if(j == 5)
j=0;

grid.addView(t);
}
}

您需要在您的类中实现 OnClickListener。然后你必须重写 onClick 方法:

 @Override
public void onClick(View v) {
switch(v.getId()){

case // switch the ids of your views by calling getId method on them
}
}

关于Android onClickListener 不触发 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16174185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com