ドローアブルの単純なアルファ アニメーションに問題があります。以下に、問題を説明するテスト プロジェクトがあります。
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() を呼び出さないと、アニメーションはありません。他の例 (完全ではない) を見ると、シェイプ ドローアブルはアニメーターを使用してのみアニメーション化する必要があるようです。ビューで手動で postInvalidate() を呼び出す必要はありません...
それで、私の理解は正しいですか、ビュー全体を自分で無効にする必要がありますか? その場合、ビュー全体が「再描画」されるのでしょうか、それとも汚れた領域だけでしょうか?
ありがとう