Why don't inflated views respond to click listeners?
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 );
开发者_JAVA百科 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.
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.
Turns out I need to call setContentView( rootLayout )
.
精彩评论