阅读量:0
要实现拖拽动画,可以根据手势事件来获取用户拖拽的位置信息,然后根据这个位置信息来更新View的位置,从而实现拖拽动画。以下是一个简单的实现示例:
- 创建一个自定义View,重写onTouchEvent方法,处理拖拽事件:
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; } }
- 在Activity中使用DragView,并添加拖拽动画:
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的透明度会降低,松开时透明度会恢复。你可以根据需要添加更多动画效果,比如缩放、旋转等。