2022年7月24日

Android Drag View API

 



import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;


public class Drag_listener  implements  View.OnTouchListener{

    public interface ActionListener {

        public  void envent_down(MotionEvent event);
        public  void event_move(MotionEvent event);
        public  void event_up(MotionEvent event);

    }

    public  ActionListener actionListener=null;
    private final static float CLICK_DRAG_TOLERANCE = 10;
    private  float down_rowx,down_rowy;
    private  float dx,dy;


    public   boolean	onTouch(View view, MotionEvent event){


        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)view.getLayoutParams();

            switch (event.getAction()){


                case MotionEvent.ACTION_DOWN:

                    down_rowx = event.getRawX();
                    down_rowy = event.getRawY();
                    dx = view.getX() - down_rowx;
                    dy = view.getY() - down_rowy;

                    if(actionListener!=null){
                        actionListener.envent_down(event);
                    }

                    break;

                case MotionEvent.ACTION_MOVE:
                    int viewWidth = view.getWidth();
                    int viewHeight = view.getHeight();

                    View viewParent = (View)view.getParent();
                    int parentWidth = viewParent.getWidth();
                    int parentHeight = viewParent.getHeight();

                    float newX = event.getRawX() + dx;
                    newX = Math.max(layoutParams.leftMargin, newX);
                    newX = Math.min(parentWidth - viewWidth - layoutParams.rightMargin, newX);

                    float newY = event.getRawY() + dy;
                    newY = Math.max(layoutParams.topMargin, newY);
                    newY = Math.min(parentHeight - viewHeight - layoutParams.bottomMargin, newY);

                    view.animate()
                            .x(newX)
                            .y(newY)
                            .setDuration(0)
                            .start();

                    if(actionListener!=null){
                        actionListener.event_move(event);
                    }
                    break;

                case MotionEvent.ACTION_UP:

                    float upRawX = event.getRawX();
                    float upRawY = event.getRawY();

                    float upDX = upRawX - down_rowx;
                    float upDY = upRawY - down_rowy;

                    if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
                        return view.performClick();
                    }

                    if(actionListener!=null){
                        actionListener.event_up(event);
                    }

                    break;

            }



        return true;
     }




}

沒有留言:

張貼留言