2013-04-23 89 views
3

我正在开发一个使用onClickListeners翻转切片的应用程序。我在RelativeLayout中拥有整个事物。然后我有第二个RelativeLayout来包含我的所有瓷砖,以便于清理和添加。我还在xml中预定义了各种其他按钮。Android onClickListener未触发子视图

<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,这是我的自定义操作的ImageViews。我也为他们添加onClickListeners。网格变量是我上面显示的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版本,这些瓷砖似乎从未触发过单击事件。我在onClickListeners上添加了tile,然后在RelativeLayout上添加一个来测试,RelativeLayout获取该事件,但这些图块没有。

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

在较新的Android版本中,此工作正常。这让我怀疑旧版本是否会在代码中添加的视图中传递事件。

有人能告诉我我的做法对旧版本有什么不妥吗?

+0

也许尝试'setOnTouchListener()'或'的机器人:可点击= “真”'属性。除此之外,你似乎应该正常工作。 – burmat 2013-04-23 16:59:13

+0

我尝试了这些和不同的事物的许多组合,没有运气。我用尽了所有我能想到的东西。这让我疯狂。 – Xather 2013-04-24 00:32:52

+0

@Xather你有没有解决你的问题?我有类似的问题... – Mike6679 2015-01-24 03:16:23

回答

0

试试这个,

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   
     } 
    }