I have a ListView populated from a custom adapter. Each row has 1 button in it. In the xml the button has the onClick attribute passed. I have only the xml, not any OnClickListeners set. Also note that the public void myMethod (View v) exists in my CustomActivity. I get the following exception
10-02 03:01:46.463: E/AndroidRuntime(26857): java.lang.IllegalStateException: Could not find a method myClickHandler(View) in the activity class **android.app.Application** for onClick handler on view class android.widget.Button with id 'myButton'
Method in Activity:
public void myClickHandler(View v) {
... do stuff here...
}
Button XML:
<Button
android:id="@+id/myButton"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="@drawable/eye_icon"
android:onClick="myClickHandler"
/>
One Interesting note in the Exception is that the app tries to find the method in android.app.Application and not in my custom Activity.
Any suggestions?
This is one example of why the
onClick
attribute is considered broken. It is probably best to create a custom Adapter and in thegetView()
method, set theOnClickListener
manually.When creating the custom
Adapter
, I was passing as theContext
the result of thegetApplicationContext()
method. This was wrong. I should passthis
(my customActivity
) as theContext
. It works like a charm now.I'm assuming you wrote a custom adapter for this view so in your adapter when you call getView simply findElementById on the button and set the onClickListener there.
It’s important that
MyActivity
andgetContext()
ofCustomAdapter
must be the same instance. Compare yours with mine.My codes:
MyActivity.java
CustomAdapter.java
activity_my.xml
list_item_view.xml