要實(shí)現(xiàn)拖拽動(dòng)畫,可以根據(jù)手勢(shì)事件來獲取用戶拖拽的位置信息,然后根據(jù)這個(gè)位置信息來更新View的位置,從而實(shí)現(xiàn)拖拽動(dòng)畫。以下是一個(gè)簡(jiǎn)單的實(shí)現(xiàn)示例:
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;
}
});
}
}
在這個(gè)示例中,當(dāng)用戶按下時(shí),View的透明度會(huì)降低,松開時(shí)透明度會(huì)恢復(fù)。你可以根據(jù)需要添加更多動(dòng)畫效果,比如縮放、旋轉(zhuǎn)等。