【问题标题】:Why don't inflated views respond to click listeners?为什么膨胀的视图不响应点击监听器?
【发布时间】:2011-09-12 22:00:57
【问题描述】:

我正在尝试为布局中的按钮设置点击监听器。点击监听器仅在我直接调用 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>

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

【问题讨论】:

    标签: android layout onclick inflate


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多