我试图在ActionBar中集成SearchView错误(MenuItem1无法强制转换为android.widget.SearchView)

时间:2014-10-06 06:21:46

标签: android android-actionbar searchview

我正在尝试将SearchView集成到ActionBar中。我尝试了所有教程,但我仍然没有成功。这个错误一直出现(java.lang.ClassCastException:com.android.internal.view.menu.MenuItem1不能被强制转换为android.widget.SearchView)。如果有人能帮助我,我将会非常有帮助问题,因为两天..

 import android.app.SearchManager;
 import android.support.v4.app.Fragment;//I have used Fragment
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.widget.SearchView;


    // Created Options Menu 
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {

        inflater.inflate(R.menu.activity_main_actionmenu, menu);

        SearchManager searchManager=(SearchManager)   

getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView=(SearchView) menu.findItem(R.id.actionSearch);
// The error of java.lang.ClassCastException: com.android.internal.view.menu.MenuItem1 cannot  

 //be cast to android.widget.SearchView occur because of above line

searchView.setSearchableInfo(searchManager
        .getSearchableInfo(getActivity().getComponentName()));
super.onCreateOptionsMenu(menu,inflater);
}

MenuItem1.xml

<item
android:id="@+id/actionSearch"
android:actionViewClass="android.widget.SearchView"
// I think android.support.v4.app.Fragment doesnot support android.widget.SearchView
android:icon="@drawable/ic_action_search"
android:showAsAction="always"/>

1 个答案:

答案 0 :(得分:1)

尝试删除import library android.widget.SearchView,当您传递光标再次导入时,验证您有更多选项。

误解是将Cast(SearchManager)作为一个不属于你的类型的对象,如果你已经工作,请尝试这个

SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem (R.id.actionSearch) .getActionView ();