Error: Didn't find class android.view.menu (on

2019-07-25 06:28发布

问题:

I'm trying to create a single menu item. When I run my app, it crashes right when it starts up and I get the following error in LogCat:

E/AndroidRuntime(1507): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.menu" on path: /data/app/com.thing.appname-2.apk

Here is my XML:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/addEventMenu"
              android:title="Add Event"
              android:icon="@drawable/addeventimage"/>
    </menu>

The following is outside of the onCreate method (don't know if it makes a difference):

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.addEventMenu:
                //do something here when menu button is pressed
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.id.addEventMenu);
        return super.onCreateOptionsMenu(menu);
    }

I've also tried this and I get the same error:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

回答1:

I ran into the same problem before when I started Android Development...

There is a different XML file under "menu" in your project resources - this is much different from the layout XML file. Put the <menu> and <item>(s) in the "res/menu/main.xml".

Also, the Android Studio has an odd way of telling you to import stuff... make sure you use

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

and click on the red notification to import.



回答2:

I ran into the same problem when my layout file (activity_main.xml) had wrong 'style' items.

Removing the wrong items from the xml file solved it.



回答3:

I ran into a similar problem, the app crashed and I got runtime error caused by:

java.lang.ClassNotFoundException: Didn't find class "android.view.style"

Removing the 'style' items from the layout file (activity_main.xml) solved it. I assume that if the style items had been needed, a proper import would have solved the problem.



回答4:

You're probably using ActionbarSherlock. If that is the case try import

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

instead of android.view.menu