关于闪退问题:
我之前遇到过这个问题,它源于onAnimationEnd()
调用与下一个布局传递不同步的可能性。Animation
通过对视图应用变换,相对于当前位置绘制它来工作。
但是,可以在您在onAnimationEnd()
方法中移动视图之后呈现视图。在这种情况下,Animation 的转换仍然被正确应用,但 Animation 认为 View 没有改变它的原始位置,这意味着它将相对于它的 ENDING 位置而不是它的 STARTING 位置进行绘制。
我的解决方案是创建 Animation 的自定义子类并添加一个方法 ,changeYOffset(int change)
该方法修改在 Animation 方法期间应用的 y 平移applyTransformation
。我在 View 的onLayout()
方法中调用了这个新方法,并传递了新的 y 偏移量。
这是我的动画中的一些代码,MenuAnimation
:
/**
* Signal to this animation that a layout pass has caused the View on which this animation is
* running to have its "top" coordinate changed.
*
* @param change
* the difference in pixels
*/
public void changeYOffset(int change) {
fromY -= change;
toY -= change;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float reverseTime = 1f - interpolatedTime;
float dy = (interpolatedTime * toY) + (reverseTime * fromY);
float alpha = (interpolatedTime * toAlpha) + (reverseTime * fromAlpha);
if (alpha > 1f) {
alpha = 1f;
}
else if (alpha < 0f) {
alpha = 0f;
}
t.setAlpha(alpha);
t.getMatrix().setTranslate(0f, dy);
}
从 View 类:
private int lastTop;
// ...
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// the animation is expecting that its View will not be moved by the container
// during its time period. if this does happen, we need to inform it of the change.
Animation anim = getAnimation();
if (anim != null && anim instanceof MenuAnimation) {
MenuAnimation animation = (MenuAnimation) anim;
animation.changeYOffset(top - lastTop);
}
// ...
lastTop = top;
super.onLayout(changed, left, top, right, bottom);
}