我想設置一個點擊監聽,在我的佈局的按鈕。當我打電話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>
這是爲什麼?我只從第一個方法中獲取點擊事件,而不是從膨脹的視圖中獲取。