是否应该仅在UI线程上调用AnimatorUpdateListener?我有一个更新视图颜色的值动画。所以代码看起来像:
class CustomView extends View {
public void startAnimation() {
ValueAnimator animation = ValueAnimator.ofObject(new ArgbEvaluator(),
mStartColor, mEndColor);
animation.setDuration(500L);
animation = new CustomAnimatorUpdateListener(this);
}
private static class CustomAnimatorUpdateListener implements ValueAnimator.AnimatorUpdateListener {
private final WeakReference<View> mHostViewRef;
CustomAnimatorUpdateListener(@NonNull final View hostView) {
mHostViewRef = new WeakReference<>(hostView);
}
@Override
public void onAnimationUpdate(ValueAnimator animator) {
if (mHostViewRef.get() != null) {
mHostViewRef.get().setBackgroundColor((int) animator.getAnimatedValue()); // Crash on this line
}
}
}
崩溃是
NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
似乎一个线程在if检查mHostViewRef.get()!= null中变为非空,而另一个线程正在执行if块,并且它返回null然后应用程序崩溃。
我想知道,这个AnimatorUpdateListener是否总是在UI线程上调用?或者可以在后台线程?