2013-04-23 87 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   
     } 
    }