在SearchView上更改工具栏的颜色/样式,请点击 [英] Change Toolbar color/style on SearchView click

查看:156
本文介绍了在SearchView上更改工具栏的颜色/样式,请点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题.

I have simple question.

单击搜索图标时,如何将工具栏的颜色/或主题更改为白色?

How I can change Toolbar's color/or theme to white when clicked on Search icon?

无论何时单击搜索图标,我都希望工具栏为白色(后箭头为黑色/灰色).我在MenuItem中添加了 SearcView(android.support.v7.widget.SearchView)

I want Toolbar to be White(with back arrow colored black/grey) whenever search icon is clicked. I have added SearcView (android.support.v7.widget.SearchView) in MenuItem

收件人

然后,当单击后退"按钮时,恢复为原始的工具栏颜色.

And then back to original Toolbar color when Back button is clicked.

推荐答案

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按钮以扩展视图的颜色,请将其添加到您的样式中:

To change the color of back/X-buttons for expanded view add this into your styles:

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

要使颜色更改更平滑-您可以对其进行动画处理:在Android上对视图背景颜色进行动画处理

To make change of the color smoother - you can animate it: Animate change of view background color on Android

我希望这会有所帮助

这篇关于在SearchView上更改工具栏的颜色/样式,请点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆