Android 如何将 SearchWidget 添加到 ActionBar?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11276043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:39:57  来源:igfitidea点击:

How to add a SearchWidget to the ActionBar?

androidnullpointerexceptionandroid-actionbarsearchview

提问by Taig

I'm trying to add a Search-ActionView to my application (as explained here http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget). Unfortunately I keep getting a NullPointerException and I'm having a hard time detecting what's actually going wrong.

我正在尝试向我的应用程序添加 Search-ActionView(如http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget此处所述)。不幸的是,我不断收到 NullPointerException 异常,而且我很难检测到实际出了什么问题。

I created a searchable config and a searchable activity as shown on the android page. My menu .xml file looks like this:

我创建了一个可搜索的配置和一个可搜索的活动,如 android 页面上所示。我的菜单 .xml 文件如下所示:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    ...
    <item
        android:id="@+id/menu_item_search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@drawable/icon_search"
        android:showAsAction="always"
        android:title="@string/action_bar_button_search">
    </item>

</menu>

This is the method where the Exception is thrown:

这是抛出异常的方法:

public boolean onCreateOptionsMenu( Menu menu )
{
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate( R.menu.action_bar, menu );

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();

    // NullPointerException thrown here; searchView is null.
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);

    return super.onCreateOptionsMenu( menu );
}

Complete stack trace:

完整的堆栈跟踪:

FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.activities.Test.onCreateOptionsMenu(Test.java:41)
at android.app.Activity.onCreatePanelMenu(Activity.java:2444)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:408)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:759)
at com.android.internal.policy.impl.PhoneWindow.run(PhoneWindow.java:2997)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)

采纳答案by Dheeresh Singh

use this way as in link

使用这种方式作为链接

public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_bar, menu);
        MenuItem searchItem = menu.findItem(R.id.menu_item_search);
        SearchView searchView = (SearchView) searchItem.getActionView();


        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        if(null!=searchManager ) {   
         searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        }
        searchView.setIconifiedByDefault(false);

        return true;
    }

回答by Taig

Since this question is looked up quite often and I stumbled across the very same problem again and again here is a little follow up that keeps track of all necessary steps to create a SearchWidget.

由于这个问题经常被查找并且我一次又一次地偶然发现了同样的问题,因此这里有一些跟进,它跟踪了创建 SearchWidget 的所有必要步骤。

There is one tricky part about the SearchWidget though: If you use hardcoded Strings in the searchable.xml instead of resources the app will crash with a confusing error message.This took me way too many hours of my life...

不过,关于 SearchWidget 有一个棘手的部分:如果您在 searchable.xml 中使用硬编码字符串而不是资源,应用程序将崩溃并显示令人困惑的错误消息。这花了我太多的时间......

  1. Create an Activity to handle the search results

    public class Search extends Activity {}
    
  2. Add a file "searchable.xml" to your res/xml directory (use resources for hint & label!)

    <searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:hint="@string/search_hint"
        android:includeInGlobalSearch="false"
        android:label="@string/search_label"
        android:searchSettingsDescription="@string/search_global_description" />
    
  3. Create the proper menu item "main.xml" in you res/menu directory

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <item
           android:id="@+id/options_menu_main_search"
           android:actionViewClass="android.widget.SearchView"
           android:icon="@drawable/icon_magnifier"
           android:showAsAction="always"
           android:title="Search"/>
    
    </menu>
    
  4. Update your Manifest.xml: Add the search activity and specify which activities may receive search intents. Adding <meta-data android:name="android.app.default_searchable" android:value=".app.Search" />to an activitynode makes it searchable. Adding it to the applicationnode makes all activities searchable.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <application>
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".app.Search" />
    
            <activity android:name=".activities.Search" >
                <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
    
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>
    

  5. Add the SearchManager to your ActionView in every activity that should provide the SearchWidget

    public class Activity extends android.app.Activity
    {
        @Override
        public boolean onCreateOptionsMenu( Menu menu )
        {
            getMenuInflater().inflate( R.menu.main, menu );
    
            // Add SearchWidget.
            SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
            SearchView searchView = (SearchView) menu.findItem( R.id.options_menu_main_search ).getActionView();
    
            searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );
    
            return super.onCreateOptionsMenu( menu );
        }
    }
    
  1. 创建一个 Activity 来处理搜索结果

    public class Search extends Activity {}
    
  2. 将文件“searchable.xml”添加到您的 res/xml 目录(使用提示和标签资源!

    <searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:hint="@string/search_hint"
        android:includeInGlobalSearch="false"
        android:label="@string/search_label"
        android:searchSettingsDescription="@string/search_global_description" />
    
  3. 在 res/menu 目录中创建正确的菜单项“main.xml”

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <item
           android:id="@+id/options_menu_main_search"
           android:actionViewClass="android.widget.SearchView"
           android:icon="@drawable/icon_magnifier"
           android:showAsAction="always"
           android:title="Search"/>
    
    </menu>
    
  4. 更新您的 Manifest.xml:添加搜索活动并指定哪些活动可以接收搜索意图。添加<meta-data android:name="android.app.default_searchable" android:value=".app.Search" />activity节点使其可搜索。将它添加到application节点使所有活动都可搜索。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <application>
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".app.Search" />
    
            <activity android:name=".activities.Search" >
                <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
    
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>
    

  5. 在应该提供 SearchWidget 的每个活动中将 SearchManager 添加到您的 ActionView

    public class Activity extends android.app.Activity
    {
        @Override
        public boolean onCreateOptionsMenu( Menu menu )
        {
            getMenuInflater().inflate( R.menu.main, menu );
    
            // Add SearchWidget.
            SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
            SearchView searchView = (SearchView) menu.findItem( R.id.options_menu_main_search ).getActionView();
    
            searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );
    
            return super.onCreateOptionsMenu( menu );
        }
    }
    

回答by peceps

If you are using targeting Android 2.xand using android.support.v7.widget.SearchViewcheck that your menu.xml looks like this (note the yourappnamespace)

如果您使用面向Android 2.x并使用android.support.v7.widget.SearchView检查您的 menu.xml 是否如下所示(注意yourapp命名空间)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/ic_search"
        yourapp:showAsAction="always"
        yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

And in the Activity where you inflate the menu use:

并在您膨胀菜单的活动中使用:

android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) 
MenuItemCompat.getActionView(menu.findItem(R.id.search));

回答by QuinnX

SearchView getActionView returning null

SearchView getActionView 返回 null

As in the link, open your menu xml file and change

如链接中所示,打开您的菜单 xml 文件并更改

android:actionViewClass="android.widget.SearchView"

into

进入

app:actionViewClass="android.widget.SearchView" 

this worked for me

这对我有用

回答by stenlytw

I also got the same problem. In my case, change android:actionViewClassto app:actionViewClasssolved the problem (with xmlns:app="http://schemas.android.com/apk/res-auto"in <menu>tag).

我也遇到了同样的问题。就我而言,更改android:actionViewClassapp:actionViewClass解决问题(带有xmlns:app="http://schemas.android.com/apk/res-auto"in<menu>标记)。

回答by Riya Gayasen

First of all, create an XML file containing the SearchWidget to your layout folder

首先,创建一个包含 SearchWidget 的 XML 文件到您的布局文件夹

<?xml version="1.0" encoding="utf-8"?>
<SearchView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit_query"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter"
    >

</SearchView>

Then, in your activity, retrieve the action bar

然后,在您的活动中,检索操作栏

android.support.v7.app.ActionBar actionBar = getSupportActionBar();

Then add a reference to your search view

然后添加对搜索视图的引用

 actionBar.setCustomView(R.layout.custom_action_bar);
    search = (EditText) actionBar.getCustomView().findViewById(
            R.id.edit_query);

Then, set the display option for the action bar

然后,设置操作栏的显示选项

actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);

That's it.

就是这样。

Btw, you could also use my search widgetwhich takes a list of strings as an array list and displays them, according to the query entered. Once the user selects a particular result, the selected result is returned which can retrieved on the onActivityResult of the parent activity.

顺便说一句,您还可以使用我的搜索小部件,它将字符串列表作为数组列表并根据输入的查询显示它们。一旦用户选择了特定结果,就会返回所选结果,该结果可以在父活动的 onActivityResult 上检索。

回答by tpbapp

This problem is triggered by a missing intent filter:

此问题是由缺少意图过滤器触发的:

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>