Why don't inflated views respond to click listeners?

江枫思渺然 提交于 2019-12-13 03:06:49

问题


I'm trying to set a click listener for a button in my layout. The click listener is only triggered when I call findViewById() directly, and not when I take the view from the inflated layout:

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" );
    }
}

Here is my layout:

<?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>

Why is this? I only get the click event from the first method and not from the inflated view.


回答1:


You only get the click event from the first method (the one that sends "Click" to LogCat) because you don't add anything that you inflate to your view hierarchy. The second line of your onCreate() method, setContentView(R.layout.test); takes care of inflating your views from the layout file AND adding them to the activity's view hierarchy. When you do the inflation manually a few lines later, you are forgetting to add rootLayout to the view hierarchy. Without doing this, there is nothing to click and hence no output on LogCat from your other onClick() method.




回答2:


Turns out I need to call setContentView( rootLayout ).



来源:https://stackoverflow.com/questions/7394560/why-dont-inflated-views-respond-to-click-listeners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!