SearchView using AppCompat

≡放荡痞女 提交于 2019-12-03 06:57:52

问题


I implemented SearchView in Actionbar before using appcompat.v7 but when I want to use the SearchView with support library v7 it shows null exception

In style

<item android:id="@+id/action_search"
    android:title="@string/action_search"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="always|collapseActionView"
    android:actionViewClass="android.support.v7.widget.SearchView" />

In Java Class:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(this);
    return super.onCreateOptionsMenu(menu);
}

My question is how to declare SearchView in onCreateOptionsMenu to be able to set query listener?


回答1:


You should use the static methods in MenuItemCompat do deal with all AppCompat menu items. This was mentioned in this blog post as the last item under 'New Integration'. Just replace your SearchView declaration with the following.

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));

Here's a link to the MenuItemCompat documentation.

Edit: I just assumed you are using the latest version of AppCompat with the support for the new Toolbar widget.




回答2:


If you change android:actionViewClass to app:actionViewClass your existing code will continue working.



来源:https://stackoverflow.com/questions/26564960/searchview-using-appcompat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!