2011-09-12 26 views
0

我想設置一個點擊監聽,在我的佈局的按鈕。當我打電話findViewById點擊收聽只觸發()直接,而不是當我把視圖從充氣佈局:爲什麼不充氣意見作出迴應點擊聽衆?

public class MyActivity extends Activity implements View.OnClickListener { 
    private static final String TAG = "MyActivity"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 

     Button button = (Button)findViewById(R.id.mybutton); 
     button.setOnClickListener(this); 

     LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     ViewGroup rootLayout = (ViewGroup)inflater.inflate(R.layout.test, 
      (ViewGroup)findViewById(R.id.myroot), false); 
     rootLayout.getChildAt(0).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.d(TAG, "Click from inflated view"); 
      } 
     }); 
    } 

    @Override 
    public void onClick(View v) { 
     Log.d(TAG, "Click"); 
    } 
} 

這裏是我的佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/myroot" android:orientation="vertical" 
    android:layout_width="fill_parent" android:background="#ffffff" 
    android:layout_height="fill_parent"> 
    <Button android:text="Button" android:id="@+id/mybutton" 
     android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> 
</LinearLayout> 

這是爲什麼?我只從第一個方法中獲取點擊事件,而不是從膨脹的視圖中獲取。

回答

1

原來我需要調用setContentView(rootLayout)

4

你只有從第一個方法,因爲你不加你膨脹到您的視圖層次東西(發送「點擊」到logcat的一個)的單擊事件。您的onCreate()方法的第二行,setContentView(R.layout.test);需要從佈局文件膨脹的意見,並將它們添加到活動中的視圖層次的關懷。當你以後做手工通脹的幾行,你都忘了rootLayout添加到視圖層次結構。如果沒有這樣做,沒有什麼可以點擊的,因此LogCat上的其他onClick()方法沒有輸出。