禁用汉堡包以在工具栏上支持箭头动画

时间:2014-11-25 01:17:53

标签: android material-design android-toolbar

使用汉堡包实现Toolbar后退箭头动画非常容易。在我看来这个动画毫无意义,因为根据材料设计规范,导航抽屉在打开时会覆盖Toolbar。我的问题是如何正确禁用此动画并使用getSupportActionBar().setDisplayHomeAsUpEnabled(true);

显示汉堡包或后退箭头

我就是这样做的,但它看起来像是一个肮脏的黑客:

mDrawerToggle.setDrawerIndicatorEnabled(false);

if (showHomeAsUp) {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_arrow_back_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> finish());
} else {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_menu_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> toggleDrawer());
}

有关如何正确使用setDisplayHomeAsUpEnabled来切换汉堡包和后退箭头图标的任何线索?

8 个答案:

答案 0 :(得分:47)

这将禁用动画,在创建抽屉切换时,覆盖onDrawerSlide():

drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
        getToolbar(), R.string.open, R.string.close) {

    @Override
    public void onDrawerClosed(View view) {
        super.onDrawerClosed(view);
    }

    @Override
    public void onDrawerOpened(View drawerView) {
        super.onDrawerOpened(drawerView);
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        super.onDrawerSlide(drawerView, 0); // this disables the animation 
    }
};

如果您想完全删除箭头,可以添加

 super.onDrawerSlide(drawerView, 0); // this disables the arrow @ completed state

在onDrawerOpened函数的末尾。

答案 1 :(得分:12)

  

在我看来这个动画毫无意义

嗯,ActionBarDrawerToggle是动画的。

From the docs:

  

您可以通过定义来自定义动画切换   ActionBar主题中的drawerArrowStyle。

  

任何线索如何正确实现才能使用   setDisplayHomeAsUpEnabled在汉堡包和后箭头之间切换   图标?

ActionBarDrawerToggle只是一种调用ActionBar.setHomeAsUpIndicator的奇特方式。因此,无论哪种方式,您都必须致电ActionBar.setDisplayHomeAsUpEnabledtrue才能展示它。

如果您确信必须使用它,那么我建议您分别拨打ActionBarDrawerToggle.onDrawerOpened(View drawerView)ActionBarDrawerToggle.onDrawerClosed(View drawerView)

这会将DrawerIndicator位置设置为10,在DrawerArrowDrawable的箭头和汉堡状态之间切换。

在您的情况下,甚至不需要将ActionBarDrawerToggle附加为DrawerLayout.DrawerListener。如:

mYourDrawer.setDrawerListener(mYourDrawerToggle);

但更为前瞻性的方法是拨打ActionBar.setHomeAsUpIndicator一次并使用自己的汉堡包图标,你也可以通过一种风格来实现。然后,当您想要显示后退箭头时,只需调用ActionBar.setDisplayHomeAsUpEnabled并让AppCompat或框架处理其余部分。根据你的评论,我很确定这就是你要找的东西。

如果您不确定使用哪个图标the default DrawerArrowDrawable size is 24dp,则表示您想要从Google官方资料中的navigation icon set抓取ic_menu_white_24dpic_menu_black_24dp设计图标包。

您也可以将DrawerArrowDrawable复制到项目中,然后根据需要切换箭头或汉堡包状态。它是自包含的,减去一些资源。

答案 2 :(得分:4)

这是我控制位于NavigationDrawerFragment中的ActionBarDrawableToggle的函数,我在每个片段的onActivityCreated回调中调用它。职能是必要的。汉堡图标变为后箭头,后箭头可点击。方向更改由处理程序正确处理。

...

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;

...

public class NavigationDrawerFragment extends Fragment
{
    private ActionBarDrawerToggle mDrawerToggle;

    ...

    public void syncDrawerState()
    {
       new Handler().post(new Runnable()
        {
            @Override
            public void run()
            {
                final ActionBar actionBar = activity.getSupportActionBar();
                if (activity.getSupportFragmentManager().getBackStackEntryCount() > 1 && (actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != ActionBar.DISPLAY_HOME_AS_UP)
                {
                    new Handler().post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            mDrawerToggle.setDrawerIndicatorEnabled(false);
                            actionBar.setDisplayHomeAsUpEnabled(true);
                            mDrawerToggle.setToolbarNavigationClickListener(onToolbarNavigationClickListener());
                        }
                    });
                } else if (activity.getSupportFragmentManager().getBackStackEntryCount() <= 1 && (actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP)
                {
                    actionBar.setHomeButtonEnabled(false);
                    actionBar.setDisplayHomeAsUpEnabled(false);
                    mDrawerToggle.setDrawerIndicatorEnabled(true);
                    mDrawerToggle.syncState();
                }
            }
        });      
    }
}

这只是我基础片段中的onActivityCreated方法。

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    navigationDrawerFragment.syncDrawerState();
}

答案 3 :(得分:3)

我有类似的要求,花了一些时间浏览ActionBarDrawerToggle代码。你现在拥有的是最好的前进方式。

更多信息:

箭头动画的汉堡包由可绘制的实现提供 - DrawerArrowDrawableToggle。目前,我们无法控制这种抽屉对抽屉状态的反应。以下是actionVarDrawerToggle的包访问构造函数:

/**
 * In the future, we can make this constructor public if we want to let developers customize
 * the
 * animation.
 */
<T extends Drawable & DrawerToggle> ActionBarDrawerToggle(Activity activity, Toolbar toolbar,
        DrawerLayout drawerLayout, T slider,
        @StringRes int openDrawerContentDescRes,
        @StringRes int closeDrawerContentDescRes)

通过提供自己的slider实现,您可以控制它对抽屉状态的反应。 slider必须实现的界面:

/**
 * Interface for toggle drawables. Can be public in the future
 */
static interface DrawerToggle {

    public void setPosition(float position);

    public float getPosition();
}

setPosition(float)是此处的亮点 - 所有抽屉状态更改都会调用它来更新抽屉指示器。

对于您想要的行为,您的slider实施setPosition(float position)将无效。

您仍然需要:

if (showHomeAsUp) {
    mDrawerToggle.setDrawerIndicatorEnabled(false);
    // Can be set in theme
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_arrow_back_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> finish());
}

如果您没有setDrawerIndicatorEnabled(false),则您使用OnClickListener设置的setToolbarNavigationClickListener(view -> finish());将无法触发。

我们能做什么现在

仔细观察后,我发现ActionBarDrawerToggle中有您的要求。我觉得这个规定比你现在的更糟糕。但是,我会让你决定。

ActionBarDrawerToggle可让您通过界面Delegate对抽屉指示符进行某些控制。您可以通过以下方式让您的活动实现此界面:

public class TheActivity extends ActionBarActivity implements ActionBarDrawerToggle.Delegate {
....

    @Override
    public void setActionBarUpIndicator(Drawable drawableNotUsed, int i) {

        // First, we're not using the passed drawable, the one that animates

        // Second, we check if `displayHomeAsUp` is enabled
        final boolean displayHomeAsUpEnabled = (getSupportActionBar().getDisplayOptions()
            & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP;

        // We'll control what happens on navigation-icon click
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (displayHomeAsUpEnabled) {
                    finish();
                } else {
                    // `ActionBarDrawerToggle#toggle()` is private.
                    // Extend `ActionBarDrawerToggle` and make provision
                    // for toggling.
                    mDrawerToggle.toggleDrawer();
                }
            }
        });

        // I will talk about `mToolbarnavigationIcon` later on.

        if (displayHomeAsUpEnabled) {
            mToolbarNavigationIcon.setIndicator(
                          CustomDrawerArrowDrawable.HOME_AS_UP_INDICATOR);
        } else {
            mToolbarNavigationIcon.setIndicator(
                          CustomDrawerArrowDrawable.DRAWER_INDICATOR);
        }

        mToolbar.setNavigationIcon(mToolbarNavigationIcon);
        mToolbar.setNavigationContentDescription(i);
    }

    @Override
    public void setActionBarDescription(int i) {
        mToolbar.setNavigationContentDescription(i);
    }

    @Override
    public Drawable getThemeUpIndicator() {
        final TypedArray a = mToolbar.getContext()
            .obtainStyledAttributes(new int[]{android.R.attr.homeAsUpIndicator});
        final Drawable result = a.getDrawable(0);
        a.recycle();
        return result;
    }

    @Override
    public Context getActionBarThemedContext() {
        return mToolbar.getContext();
    }

    ....
}

ActionBarDrawerToggle将使用此处提供的setActionBarUpIndicator(Drawable, int)。因为我们忽略了传递的Drawable,所以我们可以完全控制将要显示的内容。

Catch:ActionBarDrawerToggle如果我们在此处将Activity参数传递为null,我们的Toolbar将作为委托:

public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
        Toolbar toolbar, @StringRes int openDrawerContentDescRes,
        @StringRes int closeDrawerContentDescRes) { .... }

而且,您需要在活动中覆盖getV7DrawerToggleDelegate()

@Nullable
@Override
public ActionBarDrawerToggle.Delegate getV7DrawerToggleDelegate() {
    return this;
}

正如你所看到的,正确的方法是做很多额外的工作。我们还没有完成。

可以使用these attributes设置动画DrawerArrowDrawableToggle的样式。如果您希望您的可绘制状态(homeAsUp&amp; hamburger)完全像默认值一样,您将需要实现它:

/**
 * A drawable that can draw a "Drawer hamburger" menu or an Arrow
 */
public class CustomDrawerArrowDrawable extends Drawable {

    public static final float DRAWER_INDICATOR = 0f;

    public static final float HOME_AS_UP_INDICATOR = 1f;

    private final Activity mActivity;

    private final Paint mPaint = new Paint();

    // The angle in degress that the arrow head is inclined at.
    private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45);
    private final float mBarThickness;
    // The length of top and bottom bars when they merge into an arrow
    private final float mTopBottomArrowSize;
    // The length of middle bar
    private final float mBarSize;
    // The length of the middle bar when arrow is shaped
    private final float mMiddleArrowSize;
    // The space between bars when they are parallel
    private final float mBarGap;

    // Use Path instead of canvas operations so that if color has transparency, overlapping sections
    // wont look different
    private final Path mPath = new Path();
    // The reported intrinsic size of the drawable.
    private final int mSize;

    private float mIndicator;

    /**
     * @param context used to get the configuration for the drawable from
     */
    public CustomDrawerArrowDrawable(Activity activity, Context context) {
        final TypedArray typedArray = context.getTheme()
            .obtainStyledAttributes(null, R.styleable.DrawerArrowToggle,
                    R.attr.drawerArrowStyle,
                    R.style.Base_Widget_AppCompat_DrawerArrowToggle);
        mPaint.setAntiAlias(true);
        mPaint.setColor(typedArray.getColor(R.styleable.DrawerArrowToggle_color, 0));
        mSize = typedArray.getDimensionPixelSize(R.styleable.DrawerArrowToggle_drawableSize, 0);
        mBarSize = typedArray.getDimension(R.styleable.DrawerArrowToggle_barSize, 0);
        mTopBottomArrowSize = typedArray
            .getDimension(R.styleable.DrawerArrowToggle_topBottomBarArrowSize, 0);
        mBarThickness = typedArray.getDimension(R.styleable.DrawerArrowToggle_thickness, 0);
        mBarGap = typedArray.getDimension(R.styleable.DrawerArrowToggle_gapBetweenBars, 0);

        mMiddleArrowSize = typedArray
            .getDimension(R.styleable.DrawerArrowToggle_middleBarArrowSize, 0);
        typedArray.recycle();

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.SQUARE);
        mPaint.setStrokeWidth(mBarThickness);

        mActivity = activity;
    }

    public boolean isLayoutRtl() {
        return ViewCompat.getLayoutDirection(mActivity.getWindow().getDecorView())
            == ViewCompat.LAYOUT_DIRECTION_RTL;
    }

    @Override
    public void draw(Canvas canvas) {
        Rect bounds = getBounds();
        final boolean isRtl = isLayoutRtl();
        // Interpolated widths of arrow bars
        final float arrowSize = lerp(mBarSize, mTopBottomArrowSize, mIndicator);
        final float middleBarSize = lerp(mBarSize, mMiddleArrowSize, mIndicator);
        // Interpolated size of middle bar
        final float middleBarCut = lerp(0, mBarThickness / 2, mIndicator);
        // The rotation of the top and bottom bars (that make the arrow head)
        final float rotation = lerp(0, ARROW_HEAD_ANGLE, mIndicator);

        final float topBottomBarOffset = lerp(mBarGap + mBarThickness, 0, mIndicator);
        mPath.rewind();

        final float arrowEdge = -middleBarSize / 2;
        // draw middle bar
        mPath.moveTo(arrowEdge + middleBarCut, 0);
        mPath.rLineTo(middleBarSize - middleBarCut, 0);

        final float arrowWidth = Math.round(arrowSize * Math.cos(rotation));
        final float arrowHeight = Math.round(arrowSize * Math.sin(rotation));

        // top bar
        mPath.moveTo(arrowEdge, topBottomBarOffset);
        mPath.rLineTo(arrowWidth, arrowHeight);

        // bottom bar
        mPath.moveTo(arrowEdge, -topBottomBarOffset);
        mPath.rLineTo(arrowWidth, -arrowHeight);
        mPath.moveTo(0, 0);
        mPath.close();

        canvas.save();

        if (isRtl) {
            canvas.rotate(180, bounds.centerX(), bounds.centerY());
        }
        canvas.translate(bounds.centerX(), bounds.centerY());
        canvas.drawPath(mPath, mPaint);

        canvas.restore();
    }

    @Override
    public void setAlpha(int i) {
        mPaint.setAlpha(i);
    } 

    // override
    public boolean isAutoMirrored() {
        // Draws rotated 180 degrees in RTL mode.
        return true;
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        mPaint.setColorFilter(colorFilter);
    }

    @Override
    public int getIntrinsicHeight() {
        return mSize;
    }

    @Override
    public int getIntrinsicWidth() {
        return mSize;
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public void setIndicator(float indicator) {
        mIndicator = indicator;
        invalidateSelf();
    }

    /**
     * Linear interpolate between a and b with parameter t.
     */
    private static float lerp(float a, float b, float indicator) {
        if (indicator == HOME_AS_UP_INDICATOR) {
            return b;
        } else {
            return a;
        }
    }
}

CustomDrawerArrowDrawable's实施是从AOSP借来的,并且被剥离以允许仅绘制两个州:homeAsUp&amp;汉堡包。您可以通过调用setIndicator(float)在这些状态之间切换。我们在我们实施的Delegate中使用了这个。此外,使用CustomDrawerArrowDrawable将允许您在xml中设置样式:barSizecolor等。即使您不需要,上面的实现可让您提供自定义动画抽屉打开和关闭

老实说,我不知道是否应该推荐这个。


如果您使用参数ActionBarDrawerToggle#setHomeAsUpIndicator(...)调用null,则应选择主题中定义的drawable:

<item name="android:homeAsUpIndicator">@drawable/some_back_drawable</item>

目前,由于ToolbarCompatDelegate#getThemeUpIndicator()中可能存在错误:

,因此不会发生这种情况
@Override
public Drawable getThemeUpIndicator() {
    final TypedArray a = mToolbar.getContext()
                 // Should be new int[]{android.R.attr.homeAsUpIndicator}
                .obtainStyledAttributes(new int[]{android.R.id.home});
    final Drawable result = a.getDrawable(0);
    a.recycle();
    return result;
}

Bug报告松散地讨论了这个问题(阅读案例4):Link


如果您决定坚持使用已有的解决方案,请考虑使用CustomDrawerArrowDrawable代替png(R.drawable.lib_ic_arrow_back_light&amp; R.drawable.lib_ic_menu_light)。对于密度/大小的桶,您不需要多个drawable,并且样式将在xml中完成。此外,最终产品将与框架相同。

mDrawerToggle.setDrawerIndicatorEnabled(false);

CustomDrawerArrowDrawable toolbarNavigationIcon 
                = new CustomDrawerArrowDrawable(this, mToolbar.getContext());    

if (showHomeAsUp) {
    toolbarNavigationIcon.setIndicator(
                           CustomDrawerArrowDrawable.HOME_AS_UP_INDICATOR);
    mDrawerToggle.setToolbarNavigationClickListener(view -> finish());
} else {
    mToolbarNavigationIcon.setIndicator(
                           CustomDrawerArrowDrawable.DRAWER_INDICATOR);
    mDrawerToggle.setToolbarNavigationClickListener(view -> toggleDrawer());
}

mDrawerToggle.setHomeAsUpIndicator(toolbarNavigationIcon);

答案 4 :(得分:3)

现在有专门的方法来禁用动画:id1

这是我使用的代码段:

toggle.setDrawerSlideAnimationEnabled(false)

答案 5 :(得分:1)

禁用onDrawerSlide()方法中的晚餐调用将停止箭头和汉堡之间的动画。只有当抽屉完全打开或完全关闭时,您才会看到切换(没有动画)。

mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.closed) {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                  //super.onDrawerSlide(drawerView, slideOffset);
            }
        };
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);

答案 6 :(得分:1)

如果您不想要动画,请不要使用ActionBarDrawerToggle。请改用以下代码。

toolbar.setNavigationIcon(R.drawable.ic_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    drawer.openDrawer(GravityCompat.START);
                }
            });

答案 7 :(得分:0)

要删除汉堡包菜单动画,您可以执行以下操作:

 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer,  mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

 toggle.setDrawerSlideAnimationEnabled(false);