Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inflated View doesn't catch onClick event

I have an template view it looks like ;

template.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/view_background"
android:gravity="center_vertical"
tools:context=".MainActivity" >

<Button
    android:id="@+id/btnMultiple"
    android:layout_width="0dp"
    android:layout_height="150dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_weight="1"
    android:background="@drawable/button_backgroundblue"
    android:onClick="btnMultiple_clicked"
    android:tag="4"
    android:text="@string/mc_abcd"
    android:textColor="@drawable/button_textcolor"
    android:textSize="@dimen/h2" />

I'm creating this view programmatically and then i'm adding this View into ViewFlipper as like ;

activity_main.java

public void btnCreateView_clicked(View view) {
    ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.flipper);

    View myView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.template, viewFlipper, false);
    viewFlipper.addView(myView);
    viewFlipper.showNext(); // Showing lastly created myView successfully. }

Also my activity has public function as like ;

activity_main.java

    public void btnMultiple_clicked(View view) {
        //Save the world !
}

When i press btnCreateView button from first view it's successfully creating template (myView) and then adding it into ViewFlipper. When i click btnMultiple i'm getting error and my application crashes ; "Could not find a method btnMultiple_clicked(View) in the activity class android.app.Application for onClick handler on view class android.widget.Button with id 'btnMultiple'" i'm sure there is existing method btnMultiple_clicked(View).

PS! If i add listener to btnMultiple programmatically it's gonna work but i wonder why "android:onClick="btnMultiple_clicked"" doesn't work ?

like image 274
Nande kore Avatar asked May 07 '13 19:05

Nande kore


1 Answers

Android looks for the method defined in the onClick attribute in the Activity. The problem in your code is that you used for the LayoutInflater initialization the Application's Context and not the Context of the Activity so the method will not be found there(the Context is passed to the View). Use:

View myView = LayoutInflater.from(this).inflate(R.layout.template, viewFlipper, false);

or any other reference that points to the Activity where those buttons will be used. This is a good example why you should use in most cases the Context of the Activity.

like image 79
user Avatar answered Oct 15 '22 17:10

user