在SearchView上单击更改工具栏颜色/样式

时间:2015-12-30 06:40:39

标签: android android-toolbar

我有一个简单的问题。

点击“搜索”图标后,如何将工具栏的颜色/主题更改为白色?

每当点击搜索图标时,我希望工具栏为白色(背面箭头为黑色/灰色)。我在MenuItem中添加了 SearcView(android.support.v7.widget.SearchView)

enter image description here

enter image description here

然后在单击“返回”按钮时返回原始工具栏颜色。

1 个答案:

答案 0 :(得分:14)

enter image description here

Activity / Fragment代码中:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_menu, menu);

    MenuItem searchMenuItem = menu.findItem(R.id.search);
    if (searchMenuItem == null) {
        return true;
    }

    searchView = (SearchView) searchMenuItem.getActionView();
    MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() {

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Set styles for expanded state here
            if (getSupportActionBar() != null) {
                getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));
            }
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Set styles for collapsed state here
            if (getSupportActionBar() != null) {
                getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLUE));
            }
            return true;
        }
    });

    return true;
}

实际menu的xml是:

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

要更改展开视图的后退/ X按钮的颜色,请将其添加到样式中:

<item name="colorControlNormal">@color/my_great_color</item>

要更改颜色更平滑 - 您可以为其设置动画:Animate change of view background color on Android

我希望,这有帮助