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>

为什么是这样?我只从第一种方法而不是从膨胀视图中获取点击事件。

4

2 回答 2

4

您只能从第一种方法(将“单击”发送到 LogCat 的方法)中获取单击事件,因为您没有将任何膨胀到视图层次结构中。onCreate() 方法的第二行,setContentView(R.layout.test);负责从布局文件中扩展视图并将它们添加到活动的视图层次结构中。当您在几行之后手动进行膨胀时,您会忘记将 rootLayout 添加到视图层次结构中。如果不这样做,就没有可点击的内容,因此您的其他 onClick() 方法不会在 LogCat 上输出任何内容。

于 2011-09-12T23:21:39.193 回答
1

原来我需要打电话setContentView( rootLayout )

于 2011-09-13T22:04:08.917 回答