背景
可以更改操作栏的背景,甚至可以在两种颜色之间设置动画,例如:
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();
}
问题
我找不到获取操作模态视图的方法,因此我可以在某些情况下更改其背景(在显示时)。
我尝试了什么
我唯一发现的是一种 hack-y 方式,它假设 Action 模式的 id 将保持不变,甚至这仅适用于“完成”按钮的 View (看起来像“V”,实际上更像是“取消”)。
我还找到了如何通过主题更改它,但这不是我需要的,因为我需要以编程方式进行。
问题
如何获取 actionMode 的 View ,或者更准确地说,如何使用动画更改其背景?
最佳答案
How do I get the view of the actionMode, or, more precisely, how can I change its background using an animation?
您有两个选择,不幸的是,这两个选择都不涉及 native 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), colorFrom, colorTo, duration);
}
使用反射:
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();
}
结果
这是在 2500
的持续时间内从 Color.BLACK
到 Color.BLUE
的动画结果的 gif:
关于android - 如何为 ActionBar 的 ActionMode 背景设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23457709/