我目前正在更新面向片段的应用程序(我有一个Activity,其FrameLayout容器作为我所有片段的主机)到Material Design.我想在更换片段时将汉堡图标设置为后箭头的动画.
基本上,如果这还不够清楚,here就是我想要实现的目标.我不想使用this library (MaterialMenu),我想使用官方的AppCompat lib来扩展可能.
由于this solution,我实现了这个效果,但是当更换片段时,我无法弄清楚如何将ActionBarDrawerToggle作为后退按钮.
所以我的问题是:如果后箭头图标仍然是ActionBarDrawerToggleonce,Fragement已被替换?在这种情况下,我如何覆盖它,以便它像onBackPressed(),而不是打开抽屉?我已经尝试了这个,但它不起作用:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().onBackPressed(); return true; } return false; }
提前致谢.
解决方法
如果你手动打开它,我认为在抽屉里面跟踪更清洁.这就是我最终做的事情:
public class ManualActionBarDrawerToggle extends ActionBarDrawerToggle { private static final float MENU_POSITION = 0f; private static final float ARROW_POSITION = 1.0f; private final int animationLength; private final DrawerLayout drawerLayout; private final Activity activity; private State currentState; private enum State { UP_ARROW,MENU } public ManualActionBarDrawerToggle(Activity activity,DrawerLayout drawerLayout,int openDrawerContentDescriptionResource,int closeDrawerContentDescriptionResource) { super(activity,drawerLayout,openDrawerContentDescriptionResource,closeDrawerContentDescriptionResource); animationLength = activity.getResources().getInteger(android.R.integer.config_shortAnimTime); this.drawerLayout = drawerLayout; this.activity = activity; currentState = State.MENU; } public void animateToBackArrow() { ValueAnimator anim = ValueAnimator.ofFloat(MENU_POSITION,ARROW_POSITION); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float slideOffset = (Float) valueAnimator.getAnimatedValue(); onDrawerSlide(drawerLayout,slideOffset); } }); anim.setInterpolator(new DecelerateInterpolator()); anim.setDuration(animationLength); anim.start(); currentState = State.UP_ARROW; } public void animateToMenu() { ValueAnimator anim = ValueAnimator.ofFloat(ARROW_POSITION,MENU_POSITION); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float slideOffset = (Float) valueAnimator.getAnimatedValue(); onDrawerSlide(drawerLayout,slideOffset); } }); anim.setInterpolator(new DecelerateInterpolator()); anim.setDuration(animationLength); anim.start(); currentState = State.MENU; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case (android.R.id.home): if (currentState == State.UP_ARROW) { activity.onBackPressed(); return true; } } return super.onOptionsItemSelected(item); } }