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

问题描述 投票:29回答:8

用hamburger实现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在汉堡包和后箭头图标之间切换?

android material-design android-toolbar
8个回答
47
投票

这将禁用动画,在创建drawerToggle时,覆盖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函数的末尾。


12
投票

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

好吧,ActionBarDrawerToggle意味着动画。

From the docs:

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

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

ActionBarDrawerToggle只是一种称为ActionBar.setHomeAsUpIndicator的奇特方式。因此,无论哪种方式,您都必须将ActionBar.setDisplayHomeAsUpEnabled调用true才能显示它。

如果您确信必须使用它,那么我建议分别调用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官方Material design图标包中的ic_menu_white_24dp中获取ic_menu_black_24dpnavigation icon set

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


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

我有类似的要求,并花了一些时间通过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参数传递为null,Activity将让我们的Toolbar充当委托:

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

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

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

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

动画DrawerArrowDrawableToggle可以使用these attributes风格。如果您希望您的可绘制状态(homeAsUp和汉堡包)与默认状态完全相同,则需要按以下方式实现:

/**
 * 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和汉堡。您可以通过调用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代替pngs(R.drawable.lib_ic_arrow_back_light和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);

3
投票

现在有专门的方法来禁用动画:toggle.setDrawerSlideAnimationEnabled(false)

这是我使用的一个片段:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    [...]

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    toggle.setDrawerSlideAnimationEnabled(false);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
}

1
投票

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

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

1
投票

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

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

0
投票

要删除汉堡包菜单动画,您可以这样做:

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

 toggle.setDrawerSlideAnimationEnabled(false); 
© www.soinside.com 2019 - 2024. All rights reserved.