Alex Rivera | Logout

InflateException: Couldn't resolve menu item onClick handler

Asked 2012-06-28T13:32:54.040
38

I asked this question 6 years ago. In the meantime Android development best practices have changed, and I have become a better developer.

Since then, I have realized that using the onClick XML attribute is a bad practice, and have removed it from any code base I work on.

All of my click handlers are now defined in the code of the app, not the XML layouts!

My reasons for never using onClick are

  1. it is easy to make a mistake in the value of the onClick XML attribute, which will then result in a run-time error
  2. a developer might refactor the name of the click handler method, without realizing it is called from a layout (see reason 1)
  3. finding out which method is actually being called is not always obvious. Especially if the layout is being used by a Fragment
  4. separating the concerns of layout vs behavior is good. Using onClick mixes them up, which is bad!

I hope I have convinced you to never use onClick in a layout :) !

Below is my original question, which is a pretty good illustration of why using onClick is a bad idea.

===

I'm defining menu items in XML, and trying to use the onClick attribute that was added in API 11. When the Activity is launched in an emulator running 4.0.3, the following Exceptions occur:

FATAL EXCEPTION: main
android.view.InflateException: Couldn't resolve menu item onClick handler 
    onFeedbackMenu in class android.view.ContextThemeWrapper

...
Caused by: java.lang.NoSuchMethodException: onFeedbackMenu 
    [interface com.actionbarsherlock.view.MenuItem]
at java.lang.Class.getConstructorOrMethod(Class.java:460)

I don't understand what is causing the Exception, since the following method is defined in my Activity

import com.actionbarsherlock.view.MenuItem;
...
public void onFeedbackMenu( MenuItem menuItem ) { 
    T
Edit
Report

1 Answer

79

I found a solution that worked for me. Usually the onClick attribute in a layout has the following method

public void methodname(View view) { 
    // actions
}

On a menu item (in this case Sherlock menu) it should follow the following signature:

public boolean methodname(MenuItem item) { 
    // actions
}

So, your problem was that your method returned void and not boolean.

answered 2012-09-18T22:41:05.517

Your Answer