android - 如何在 Material Design 工具栏上添加搜索按钮

标签 android material-design

我正在尝试在设置弹出窗口的左侧添加搜索按钮,但我无法在工具栏中添加。

这是我的 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>

这是我的 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" />

我得到工具栏但没有得到搜索按钮?

最佳答案

像这样在您的菜单文件夹中添加 menu_search.xml。

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

并在您的 Activity 类中覆盖此方法

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

关于android - 如何在 Material Design 工具栏上添加搜索按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893534/

相关文章:

android - Fabric crashlytics 到 Firebase 迁移

android - 我如何更改 BadgeDrawable Android 中的背景颜色

java - 如何交替两个imageview?安卓

java - 禁用后退,最近的应用程序按钮,电源按钮,主页和主页长按按钮

android - 如何从一项 Activity 开始另一项 Activity

现有 recyclerView 适配器的 Android 可扩展 cardView

java - MaterialButton 与 Button 的尺寸差异

html - 使元素溢出到父元素之外

android - 如何更改 TextInputLayout 提示文本的背景颜色

android - 增加 SwitchCompat 的轨道长度