如何以编程方式设置工具栏collapseIcon颜色

时间:2017-07-04 10:55:50

标签: android android-actionbar toolbar searchview

我想在显示搜索时更改工具栏中后退按钮的颜色(带圆圈的白色箭头)。

enter image description here

enter image description here

我设法改变了所有其他元素的颜色,但我仍然坚持使用后箭头颜色。

我可以从xml:

设置collapseIcon(后箭头drawable)
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:collapseIcon=I_WANT_TO_SET_THIS_PROGRAMMATICALLY>

我将app:collapseIcon设置为我想要的任何可绘制的,但是,我需要动态设置它。

我在这里找到的建议都不适合我。

不是这个:

final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable. abc_ic_ab_back_material);
upArrow.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(upArrow);

或者这个:

appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
        toolbar.setNavigationIcon(d);

//        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
//        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(d);
            }
        });

我找不到任何其他东西。

有人可以帮忙吗?

谢谢

1 个答案:

答案 0 :(得分:3)

终于搞定了......

这对我有用:

final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBar = (AppBarLayout) findViewById(R.id.appbar);
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof ImageButton) {
                ImageButton btn = (ImageButton) view;
                Drawable drawable = btn.getDrawable();
                drawable.setColorFilter(new_button_color, PorterDuff.Mode.SRC_ATOP);
                btn.setImageDrawable(drawable);
            }
        }
    }
});
相关问题