前棒棒糖中的android StateListAnimator

时间:2015-05-30 11:06:30

标签: android material-design

我越来越多地搜索了,但我还没找到任何答案。那么请告诉我如何在前Lollipop中使用 AnimatorInflater.loadStateListAnimator(..) view.setStateListAnimator(..)方法,有什么办法可以代替那些?

1 个答案:

答案 0 :(得分:3)

StateListAnimator是状态发生变化时启动的Animator。可以在较旧版本的Android上实现该功能。我正致力于在Carbon中向后移植那些,但目前该库仅支持高程动画。

要实现状态动画扩展a View,并覆盖 drawableStateChanged

397     @Override 
398     protected void drawableStateChanged() { 
399         super.drawableStateChanged(); 
402         if (stateAnimators != null) 
403             for (StateAnimator animator : stateAnimators) 
404                 animator.stateChanged(getDrawableState()); 
405     } 

然后使用您希望拥有的状态动画实现an animator

23     @Override 
24     protected void onPressedChanged() { 
25         if (pressed) { 
26             setTranslationZ(pressedElevation); 
27         } else { 
28             setTranslationZ(0); 
29         } 
30     } 
31 

32     private void setTranslationZ(float translationZ) { 
33         if (view.getTranslationZ() == translationZ || view.getElevation() == 0) 
34             return; 
35         ValueAnimator animator = ValueAnimator.ofFloat(view.getTranslationZ(), translationZ); 
36         animator.setInterpolator(new AccelerateDecelerateInterpolator()); 
37         animator.setDuration(300); 
38         animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 
39             @Override 
40             public void onAnimationUpdate(ValueAnimator animation) { 
41                 view.setTranslationZ((Float) animation.getAnimatedValue()); 
42             } 
43         }); 
44         animator.start(); 
45     } 

一个简单的state change detector class(每个动画师的超类):

10     public void stateChanged(int[] states) { 
11         boolean newPressed = false, newEnabled = false, newChecked = false; 
12         for (int state : states) { 
13             if (state == android.R.attr.state_enabled) { 
14                 newEnabled = true; 
15             } else if (state == android.R.attr.state_pressed) { 
16                 newPressed = true; 
17             } else if (state == android.R.attr.state_checked) { 
18                 newChecked = true; 
19             } 
20         } 
21         if (pressed != newPressed) { 
22             pressed = newPressed; 
23             onPressedChanged(); 
24         } 
25         if (enabled != newEnabled) { 
26             enabled = newEnabled; 
27             onEnabledChanged(); 
28         } 
29         if (checked != newChecked) { 
30             checked = newChecked; 
31             onCheckedChanged(); 
32         } 
33     } 

为所有视图设置正确的状态动画制作者非常复杂且耗时,但您可以通过在drawableStateChanged中添加动画来实现这一点。