要實現拖拽動畫,可以根據手勢事件來獲取用戶拖拽的位置信息,然后根據這個位置信息來更新View的位置,從而實現拖拽動畫。以下是一個簡單的實現示例:
public class DragView extends View {
private float lastX;
private float lastY;
public DragView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
float offsetX = x - lastX;
float offsetY = y - lastY;
layout((int) (getLeft() + offsetX), (int) (getTop() + offsetY),
(int) (getRight() + offsetX), (int) (getBottom() + offsetY));
break;
}
return true;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DragView dragView = findViewById(R.id.drag_view);
dragView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
ObjectAnimator.ofFloat(dragView, "alpha", 1f, 0.5f).start();
break;
case MotionEvent.ACTION_UP:
ObjectAnimator.ofFloat(dragView, "alpha", 0.5f, 1f).start();
break;
}
return false;
}
});
}
}
在這個示例中,當用戶按下時,View的透明度會降低,松開時透明度會恢復。你可以根據需要添加更多動畫效果,比如縮放、旋轉等。