DragView.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.xunao.effectdemo.dragview;
  2. import android.content.Context;
  3. import android.os.Build;
  4. import android.util.AttributeSet;
  5. import android.view.MotionEvent;
  6. import android.widget.RelativeLayout;
  7. import androidx.annotation.Nullable;
  8. import androidx.annotation.RequiresApi;
  9. /**
  10. * author : 程中强
  11. * e-mail : 740479946@qq.com
  12. * date : 2022/8/1013:27
  13. * desc :
  14. * version: 1.0
  15. */
  16. public class DragView extends RelativeLayout {
  17. public DragView(Context context) {
  18. super(context);
  19. }
  20. public DragView(Context context, @Nullable AttributeSet attrs) {
  21. super(context, attrs);
  22. }
  23. public DragView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  24. super(context, attrs, defStyleAttr);
  25. }
  26. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  27. public DragView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
  28. super(context, attrs, defStyleAttr, defStyleRes);
  29. }
  30. private float downX;
  31. private float downY;
  32. private long downTime;
  33. @Override
  34. public boolean onTouchEvent(MotionEvent event) {
  35. super.onTouchEvent(event);
  36. if (this.isEnabled()) {
  37. switch (event.getAction()) {
  38. case MotionEvent.ACTION_DOWN:
  39. downX = event.getX();
  40. downY = event.getY();
  41. break;
  42. case MotionEvent.ACTION_MOVE:
  43. final float xDistance = event.getX() - downX;
  44. final float yDistance = event.getY() - downY;
  45. if (xDistance != 0 && yDistance != 0) {
  46. int l = (int) (getLeft() + xDistance);
  47. int r = (int) (getRight() + xDistance);
  48. int t = (int) (getTop() + yDistance);
  49. int b = (int) (getBottom() + yDistance);
  50. this.layout(l, t, r, b);
  51. }
  52. break;
  53. case MotionEvent.ACTION_UP:
  54. setPressed(false);
  55. break;
  56. case MotionEvent.ACTION_CANCEL:
  57. setPressed(false);
  58. break;
  59. default:
  60. break;
  61. }
  62. return true;
  63. }
  64. return false;
  65. }
  66. }