change back arrow image in Actionbar with appcompat-v7

前端 未结 3 1282
独厮守ぢ
独厮守ぢ 2021-01-20 16:58

I have an Actionbar from android.support.v7.widget.Toolbar. It has hamburger image with animation to back arrow, I want to change back arrow from &

3条回答
  •  孤城傲影
    2021-01-20 17:24

    There are at least half a dozen ways to do this, but probably the simplest and shortest is to use reflection to grab the ActionBarDrawerToggle's Drawable, and flip its direction.

    This example wraps that functionality in a subclass, and should work no matter your ActionBar/Activity setup (provided the original class worked there in the first place).

    public class FlippedDrawerToggle extends ActionBarDrawerToggle {
        public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
            int openDrawerContentDescRes, int closeDrawerContentDescRes) {
    
            this(activity, drawerLayout, null,
                openDrawerContentDescRes, closeDrawerContentDescRes);
        }
    
        public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
            Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
    
            super(activity, drawerLayout, toolbar,
                 openDrawerContentDescRes, closeDrawerContentDescRes);
    
            try {
                Field sliderField = ActionBarDrawerToggle.class.getDeclaredField("mSlider");
                sliderField.setAccessible(true);
                DrawerArrowDrawable arrow = (DrawerArrowDrawable) sliderField.get(this);
                arrow.setDirection(DrawerArrowDrawable.ARROW_DIRECTION_RIGHT);
            }
            catch (NoSuchFieldException | IllegalAccessException e) {
                // Fail silently
            }
        }
    }
    

    This will only change the direction of the toggle's image. If you actually want the whole ActionBar/Toolbar to be flipped, you should instead change the layout's direction accordingly.

提交回复
热议问题