美文网首页
Android View拖拽跟随手指移动

Android View拖拽跟随手指移动

作者: Android刘东 | 来源:发表于2020-05-08 16:16 被阅读0次
    package test.view;
    
    import android.content.Context;
    import android.os.Build;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.View;
    
    import androidx.annotation.Nullable;
    import androidx.annotation.RequiresApi;
    
    import com.zhisheng.test.R;
    
    /**
     * 实现功能根据手指滑动
     */
    public class MyView extends View {
        int x1=0, x2=0, y1=0, y2=0;
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        public MyView(Context context) {
            super(context);
            init(context);
        }
    
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        public MyView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init(context);
        }
    
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context);
        }
    
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        void init(Context context) {
          
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            onMyTouch(event);
            return true;
        }
    
        void onMyTouch(MotionEvent event) {
    
    
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    y1 = (int)event.getY();
                    x1 = (int)event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    x2 = (int)event.getX();
                    y2 = (int)event.getY();
                    layout(x2-x1+getLeft(), y2-y1+getTop(), x2-x1+getRight(), y2-y1+getBottom());
                    break;
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Android View拖拽跟随手指移动

          本文链接:https://www.haomeiwen.com/subject/ldnfnhtx.html