欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义跟随手指移动view

程序员文章站 2022-06-09 09:48:50
...
public class MoveView extends AppCompatButton {
    int mLastX;
    int mLastY;
    public MoveView(Context context) {
        super(context);
    }
    public MoveView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //获取手指当前的坐标
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();

        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
                //现在手指的坐标 - 上次view的坐标
                int deltaX= x - mLastX;
                int deltaY = y- mLastY;

                Log.d("shj--","move ,deltax:"+deltaX+" deltay:"+deltaY);

                //用nineoldandroids实现
                int translationx = (int) (ViewHelper.getTranslationX(this)+deltaX);
                int translationy = (int) (ViewHelper.getTranslationY(this)+deltaY);
                ViewHelper.setTranslationX(this,translationx);
                ViewHelper.setTranslationY(this,translationy);

                break;
        }
        mLastY = y;
        mLastX = x;
        return true;
    }
}
相关标签: 滑动