使用AppCompat的SearchView [英] SearchView using AppCompat

查看:256
本文介绍了使用AppCompat的SearchView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用appcompat.v7之前在Actionbar中实现了SearchView 但是当我想将SearchView与支持库v7一起使用时,它会显示null异常

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

风格

<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" />

在Java类中:

@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);
}

我的问题是如何在onCreateOptionsMenu中声明SearchView以便能够设置查询侦听器?

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

推荐答案

您应该使用MenuItemCompat中的静态方法来处理所有AppCompat菜单项.在此博客帖子中,这是新建"下的最后一项一体化'.只需将您的SearchView声明替换为以下内容即可.

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));

这里是 修改: 我只是假设您使用的是最新版本的AppCompat,并且支持新的Toolbar小部件.

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

这篇关于使用AppCompat的SearchView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆