InflateException: Couldn't resolve menu item onClick handler

后端 未结 7 798
情书的邮戳
情书的邮戳 2020-12-08 19:12

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

7条回答
  •  悲哀的现实
    2020-12-08 19:50

    Although this is a bit out of date, here is the reason for the exception. When you look into the sources of android API 15 (4.0.3-4.0.4) in the class MenuInflater you will see this method:

    public InflatedOnMenuItemClickListener(Context context, String methodName) {
    mContext = context;
    Class c = context.getClass();
    try {
        mMethod = c.getMethod(methodName, PARAM_TYPES);
    } catch (Exception e) {
        InflateException ex = new InflateException(
                "Couldn't resolve menu item onClick handler " + methodName +
                " in class " + c.getName());
        ex.initCause(e);
        throw ex;
    }
    

    This is were the exception happens, as Junique already pointed out. However the removing of the app theme is just a workaround and no real option. As we see the method tries to find the Callback method on the class of the context item passed. So instead of calling getMenuInflater() in onCreateOptionsMenu you should call new MenuInflater(this), so that this is passed as a context and then the code will work.

    You can still use getMenuInflater() for other api versions if you just use an if statement like this:

    if (Build.VERSION.SDK_INT > 15)
            inflater = getMenuInflater();
        else
            inflater = new MenuInflater(this);
    

    I don't actually know if the bug happens in api versions under 15 too, so i just generally used the save version.

提交回复
热议问题