How to add search button on toolbar in material design

坚强是说给别人听的谎言 提交于 2019-12-08 19:18:59

问题


I am trying to add search button on left side of settings pop up but i am not able to add in toolbar.

Here is my code of menu.xml :

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.materialtheme.MainActivity" >

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_launcher"
        android:menuCategory="secondary"
        android:showAsAction="ifRoom"
        android:title="@string/action_search"/>
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>

and here is my toolbar.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:elevation="4dp"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

I am getting toolbar but not getting search button ?


回答1:


Use app:showAsAction="always" in your menu.xml with xmlns:app="http://schemas.android.com/apk/res-auto"> in your menu tag




回答2:


Add menu_search.xml in your menu folder like this.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_search"
    android:orderInCategory="200"
    android:title="Search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always"/>

And override this method in your Activity class

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);

    // Associate searchable configuration with the SearchView
   // SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    // searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(this);
    return super.onCreateOptionsMenu(menu);
}


来源:https://stackoverflow.com/questions/29893534/how-to-add-search-button-on-toolbar-in-material-design

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