Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Toolbar collapseIcon color programmatically

I want to change the color of the back button in the toolbar when a search is displayed (the circled white arrow).

enter image description here

enter image description here

I managed to change the color of all other elements and I am stuck with the back arrow color.

I can set the collapseIcon (back arrow drawable) from xml:

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

I set app:collapseIcon to whatever drawable I want and that works, however, I need to set it dynamically.

None of the suggestions I found here work for me.

not this:

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

or this:

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

Neither anything else I found.

Can anyone please help?

Thank you

like image 794
Guy S Avatar asked Oct 17 '22 09:10

Guy S


1 Answers

Finally got it...

This is what worked for me:

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);
            }
        }
    }
});
like image 142
Guy S Avatar answered Oct 21 '22 06:10

Guy S