我遇到了一个简单的drawable alpha动画。 Bellow你有一个测试项目来说明问题。
持有ShapeDrawable的类
public class CustomDrawable {
public ShapeDrawable shapeDrawable;
public CustomDrawable(int left, int top, int right, int bottom, int color) {
shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.setBounds(new Rect(left, top, right, bottom));
shapeDrawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
shapeDrawable.getPaint().setColor(Color.BLUE);
}
public ShapeDrawable getShapeDrawable() {
return shapeDrawable;
}
}
自定义视图
public class CustomView extends View {
private CustomDrawable drawable;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawable.getShapeDrawable().draw(canvas);
}
public void animateDrawable() {
ValueAnimator va = ValueAnimator.ofInt(255, 0);
va.setDuration(1000);
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int alpha;
@Override
public void onAnimationUpdate(ValueAnimator animation) {
alpha = (int) animation.getAnimatedValue();
drawable.getShapeDrawable().setAlpha(alpha);
drawable.getShapeDrawable().getPaint().setAlpha(alpha);
// This works but invalidates the whole view...
//postInvalidate();
}
});
va.start();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
drawable = new CustomDrawable(0, 0, h/2, w/2, Color.MAGENTA);
}
}
活动
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private CustomView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customView = (CustomView) findViewById(R.id.customView);
Button fadeOutBtn = (Button) findViewById(R.id.fadeOut);
fadeOutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customView.animateDrawable();
}
});
}
}
如果我没有在animateDrawable中调用postnvalidate(),那么就没有动画了。看到其他示例(非完整)似乎只能通过使用动画制作器绘制形状drawable,无需在视图中手动调用postInvalidate()...
那么,我的理解是否正确,我是否需要自己使整个视图无效?如果是这样的话,整个观点会被“重新粉刷”还是只是肮脏的地区?
由于