zihadrizkyef
zihadrizkyef

Reputation: 1941

menu.findItem returns null with v7 action bar

I am learning about action bar in Android Studio from Android Hive. Unfortunatelly i use v7 action bar and androidhive use built-in action bar that might makes a little different. The problem is at search view part.

MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainmenu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    System.out.println("Search Manager : "+searchManager);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    System.out.println("Search View : "+searchView);
    //searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return super.onCreateOptionsMenu(menu);
}

mainmenu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    android:title="Search"
    app:showAsAction="always"
    android:actionViewClass="android.widget.SearchView" />
</menu>

The command line says that the searchView is null. I have changed android:actionViewClass to app:actionViewClass but it said android.widget.SearchView cannot be cast to android.support.v7.widget.SearchView

For full code, you can see here

How to fix?

Upvotes: 2

Views: 1109

Answers (1)

Pratik Panawala
Pratik Panawala

Reputation: 101

you should use in

app:actionViewClass="android.support.v7.widget.SearchView"

instead of

android:actionViewClass="android.widget.SearchView" 

I hope This would be help you.

Upvotes: 2

Related Questions