How to animate background of ActionMode of the ActionBar?

大憨熊 提交于 2019-12-04 07:49:01

How do I get the view of the actionMode, or, more precisely, how can I change its background using an animation?

You have two choices, unfortunately neither of which involve native ActionMode APIs:

The ActionBarContextView is responsible for controlling the ActionMode

  1. Use Resources.getIdentifier to call Activity.findViewById and pass in the ID the system uses for the ActionBarContextView
  2. Use reflection to access to Field in ActionBarImpl

Here's an example of both:

Using Resources.getIdentifier:

private void animateActionModeViaFindViewById(int colorFrom, int colorTo, int duration) {
    final int amId = getResources().getIdentifier("action_context_bar", "id", "android");
    animateActionMode(findViewById(amId), colorFrom, colorTo, duration);
}

Using reflection:

private void animateActionModeViaReflection(int colorFrom, int colorTo, int duration) {
    final ActionBar actionBar = getActionBar();
    try {
        final Field contextView = actionBar.getClass().getDeclaredField("mContextView");
        animateActionMode((View) contextView.get(actionBar), colorFrom, colorTo, duration);
    } catch (final Exception ignored) {
        // Nothing to do
    }
}

private void animateActionMode(final View actionMode, final int from, int to, int duration) {
    final ValueAnimator va = ValueAnimator.ofObject(new ArgbEvaluator(), from, to);
    final ColorDrawable actionModeBackground = new ColorDrawable(from);
    va.addUpdateListener(new AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(final ValueAnimator animator) {
            actionModeBackground.setColor((Integer) animator.getAnimatedValue());
            actionMode.setBackground(actionModeBackground);
        }

    });
    va.setDuration(duration);
    va.start();
}

Results

Here's a gif of the results animating from Color.BLACK to Color.BLUE at a duration of 2500:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!