使用appcompat-v7

时间:2016-06-12 10:57:28

标签: android android-actionbar

Actionbar来自android.support.v7.widget.Toolbar。它有汉堡包图像,动画到后箭头,我想从< - to - >更改后退箭头。我该如何在Android Studio中执行此操作?

我在某处用setHomeAsUpIndicator()方法更改了它,但它更改了汉堡包按钮,它没有动画回箭头。

3 个答案:

答案 0 :(得分:2)

至少有六种方法可以做到这一点,但最简单和最简单的方法是使用反射来抓住ActionBarDrawerToggle Drawable,然后翻转方向。< / p>

此示例将该功能包装在子类中,无论您的ActionBar / Activity设置如何(前提是原始类在那里工作)都应该有效。

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

这只会改变切换图像的方向。如果您确实希望翻转整个ActionBar / Toolbar,则应相应地更改布局的方向。

答案 1 :(得分:0)

试试这个:

//Find the action bar for customizations
    final ActionBar ab = getSupportActionBar();
    assert ab != null;

    //Make the action bar display an up arrow and set its drawable and color
    ab.setDisplayHomeAsUpEnabled(true);
    final Drawable upArrow = ResourcesCompat.getDrawable(
            getResources(),
            R.drawable.abc_ic_ab_back_mtrl_am_alpha, //this is the <- arrow from android resources. Change this to the thing you want.
            null);
    assert upArrow != null;
    upArrow.setColorFilter(
            ContextCompat.getColor(
                    getApplicationContext(),
                    R.color.white // change this to the color you want (or remove the setColorFilter call)
            ),
            PorterDuff.Mode.SRC_ATOP);
    ab.setHomeAsUpIndicator(upArrow);

答案 2 :(得分:0)

mDrawerToggle = new ActionBarDrawerToggle...mDrawerToggle.syncState();之间添加此条件,如下所示:

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);


if (getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL)
{
      toolbar.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}


mDrawerToggle.syncState();