android – 如何动画ActionBar的ActionMode背景?

背景

可以更改操作栏的背景,甚至可以在两种颜色之间进行动画处理,如下所示:

public static void animateBetweenColors(final ActionBar actionBar,final int colorFrom,final int colorTo,final int durationInMs) {
    final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(),colorFrom,colorTo);
    colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
        ColorDrawable colorDrawable = new ColorDrawable(colorFrom);

        @Override
        public void onAnimationUpdate(final ValueAnimator animator) {
            colorDrawable.setColor((Integer) animator.getAnimatedValue());
            actionBar.setBackgroundDrawable(colorDrawable);
        }
    });
    if (durationInMs >= 0)
        colorAnimation.setDuration(durationInMs);
    colorAnimation.start();
}

问题

我无法找到一种获取动作模式视图的方法,因此我可以在某些情况下更改其背景(当它显示时).

我尝试了什么

我发现的只是一种黑客方式,它假定动作模式的id将保持不变,甚至这只适用于“完成”按钮(看起来像“V”的按钮)的视图实际上更像是“取消”).

我还发现了如何通过主题更改它,但这不是我需要的,因为我需要以编程方式进行.

这个问题

如何获取actionMode的视图,或者更确切地说,如何使用动画更改其背景?

解决方法

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

您有两个选择,遗憾的是它们都不涉及本机ActionMode API:

ActionBarContextView负责控制ActionMode

>使用Resources.getIdentifier调用Activity.findViewById并传入系统用于ActionBarContextView的ID
>使用反射在ActionBarImpl中访问Field

以下是两者的示例:

使用Resources.getIdentifier:

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

使用反射:

private void animateActionModeViaReflection(int colorFrom,int duration) {
    final ActionBar actionBar = getActionBar();
    try {
        final Field contextView = actionBar.getClass().getDeclaredField("mContextView");
        animateActionMode((View) contextView.get(actionBar),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();
}

结果

这是一个结果的GIF,从持续时间为2500的Color.BLACK到Color.BLUE:

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...