2012-03-08 89 views
0

我正在爲使用Eclipse和Android SDK的Android設備開發應用程序; 我想用相同的OnClickListener添加一些ImageButtons(在運行時)。問題在於OnClickListener僅適用於第一個添加的按鈕。 對於所有下一個按鈕,onClick事件根本不會觸發。Android:運行時OnClickListener不起作用

有人已經遇到(並解決了)這個問題嗎?

public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { 
    ImageButton myButton= new ImageButton(this); 
    myButton.setMaxHeight(140); 
    myButton.setMaxWidth(140);  
    myButton.setPadding(0, 0, 0, 0); 
    myButton.setAdjustViewBounds(true); 
    myButton.setImageResource(resId); 

    myButton.setOnClickListener(new View.OnClickListener() {    
     public void onClick(View v) { 

      // TODO Auto-generated method stub 

     } 
    }); 

    myRelativeLayout.addView(myButton, 0); 
} 
+0

myButton.setFocusable(假)......會發生什麼? – 2012-03-08 11:47:00

+0

你爲零零索引始終添加視圖? – viplezer 2012-03-08 11:47:40

+1

我只看到1個按鈕。你的日誌中有什麼錯誤? – jmishra 2012-03-08 11:48:05

回答

0

你總是將在第0位置的按鈕。

myRelativeLayout.addView(myButton, 0); 

所以,你只需要創建新的按鈕,並將其添加爲「第一個按鈕」,這可能是爲什麼你只看到工作。您之前創建的按鈕會丟失。

+0

我試圖添加按鈕在不同的位置(使用全局計數器),但不去:運行時的結果是相同的。 – gldm 2012-03-08 14:19:56

+0

你如何測試OnClick不會觸發? – 2012-03-10 10:54:55

0

添加視圖後,設置的點擊收聽這樣

final int count = myRelativeLayout.getChildCount(); 
    for (int i = 0; i < count; i++) { 
     View child = myRelativeLayout.getChildAt(i); 

     child.setOnClickListener(new View.OnClickListener() { 

         public void onClick(View v) { 

       // TODO Auto-generated method stub 

      } 
      }); 
+0

嗨gldm,你是否與我的答案一起工作它對我有效。如果你需要,我可以把詳細的代碼 – almuneef 2012-03-09 05:07:04

相關問題