ActionBar Mic Button(Voice Search) in SearchView

╄→尐↘猪︶ㄣ 提交于 2019-11-28 22:05:50
moonsweel

First, you should read this

AndroidManifest.xml for your activity with searchview widget (singleTop is necessary, please read the link above):

<activity android:name=".activities.MainActivity" 
    android:configChanges="orientation|screenSize" 
    android:launchMode="singleTop" >
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
</activity>

Create .../res/xml/searchable.xml with this:

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/hint"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"/>

Modify onCreateOptionsMenu (last two lines are matter)

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

    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint(getResources().getString(R.string.hint));

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}

And finally override onNewIntent():

@Override
protected void onNewIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        doSearch(query);
    }
}

After these changes you will see a mic button in a searchview.

Please check in your code if you didn't call:

 searchView.setIconifiedByDefault(true)

By removing it you should see the 'voice' icon.

just put the android:launchMode="singleTop" in your Manifest's activity tag

<activity android:name=".Activity.MainActivity"
            android:launchMode="singleTop"
            >
          ....
            <intent-filter>
                <action android:name="android.intent.action.SEARCH"></action>
            </intent-filter>
            <meta-data android:name="android.app.default_searchable"
                android:value=".Activity.MainActivity"
                ></meta-data>

            <meta-data android:name="android.app.searchable"
                android:resource="@xml/searchable">

            </meta-data>

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