悬浮按钮拖动布局

本文介绍了一种自定义DragFrameLayout布局实现视图拖拽的方法。通过重写触摸事件,实现了视图的拖拽与点击功能,并提供监听器来响应拖拽位置变化和点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class DragFrameLayout extends FrameLayout {

    private View view;

    private int width, heigh;

    private int screenWid, screenHei;

    private boolean isClickDrag = false;

    private boolean isTouchDrag = false;

    private float startX, startY;

    private CheckClick checkClick = new CheckClick();
//===============================begain 点击监听器=============================================
    private DragImageClickListener dragImageListener;

    public DragImageClickListener getDragImageListener() {
        return dragImageListener;
    }

    public void setDragImageListener(DragImageClickListener dragImageListener) {
        this.dragImageListener = dragImageListener;
    }


    public interface DragImageClickListener {
        public abstract void onClick();
    }
    //===============================end 点击监听器=============================================

    //===============================begain 拖快位置监听器=============================================

    private DragImageLocationListener mDragImageLocationListener;

    public interface DragImageLocationListener{
        public abstract void dragLocation(boolean touchActionUp ,float x,float y);
    }

    public void setDragImageLocationListener(DragImageLocationListener dragImageLocationListener) {
        this.mDragImageLocationListener = dragImageLocationListener;
    }
    //===============================end 拖快位置监听器=============================================

    private class CheckClick implements Runnable {

        @Override
        public void run() {
            isClickDrag = false;
            Log.i("drag", "=====checkTap====");
        }

    }

    public DragFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public DragFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void dragInit(View view) {
        screenWid = getWidth();
        screenHei = getHeight();
        width = view.getWidth();
        heigh = view.getHeight();

    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

        case MotionEvent.ACTION_DOWN:
            float x = ev.getX();
            float y = ev.getY();
            Rect frame = new Rect();
            if (view == null) {
                view = findViewById(R.id.dragImg);
                dragInit(view);
            }
            view.getHitRect(frame);
            if (frame.contains((int) (x), (int) (y))) {

                isTouchDrag = true;
                startX = x;
                startY = y;
                return true;
            }
            break;

        }
        return false;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        if (changed) {
//          setDefaultLocation(160f, 178f);
        }
        super.onLayout(changed, left, top, right, bottom);

    }

    /**
     * 设置默认位置
     */
    public void setDefaultLocation(final float x,final float y) {
        if (view == null) {
            new Handler().post(new Runnable() {

                @Override
                public void run() {
                    view = findViewById(R.id.dragImg);
                    dragInit(view);
                    startX = x;
                    startY = y;
                    move(startX, startY);
                }
            });
        }

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        Rect frame = new Rect();

        switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

            view.getHitRect(frame);
            if (frame.contains((int) (x), (int) (y))) {
                startX = x;
                startY = y;
                isTouchDrag = true;
                isClickDrag = true;
                postDelayed(checkClick, ViewConfiguration.getTapTimeout());
            }
            move(x, y);
            if (mDragImageLocationListener!=null) {
                mDragImageLocationListener.dragLocation(false, x, y);
            }
            break;
        case MotionEvent.ACTION_MOVE:

            float distanX = Math.abs(x - startX);
            float distanY = Math.abs(y - startY);

            if (Math.sqrt(distanY * distanY + distanX * distanX) > 10) {
                isClickDrag = false;
            }
            move(x, y);
            if (mDragImageLocationListener!=null) {
                mDragImageLocationListener.dragLocation(false, x, y);
            }
            break;

        case MotionEvent.ACTION_CANCEL:
            isClickDrag = false;
            isTouchDrag = false;
            break;
        case MotionEvent.ACTION_UP:
            if (isClickDrag == true) {
                if (dragImageListener!=null) {
                    dragImageListener.onClick();
                }
                removeCallbacks(checkClick);
            }
            isClickDrag = false;
            isTouchDrag = false;
//          Log.d("myf", x+"========="+y);
            // 这段是把控件吸附四周
//          if (x > width && x < screenWid - width && y > heigh
//                  && y < screenHei -  heigh) {
//              int minType = minDIstance(x, y);
//              Log.i("tags", screenHei + "==mintype=" + minType);
//              switch (minType) {
//              case LEFT:
//                  x = width;
//                  break;
//              case RIGHT:
//                  x = screenWid - width;
//                  break;
//              case TOP:
//                  y = heigh;
//                  break;
//              case BOTTOM:
//                  y = screenHei - heigh;
//                  break;
//              default:
//                  break;
//              }
//              move(x, y);
//          }
            if (mDragImageLocationListener!=null) {
                mDragImageLocationListener.dragLocation(true, x, y);
            }
            break;
        case MotionEvent.ACTION_OUTSIDE:
            isClickDrag = false;
            isTouchDrag = false;
            break;
        }
        return true;
    }

    private final static int LEFT = 1;
    private final static int RIGHT = 2;
    private final static int TOP = 3;
    private final static int BOTTOM = 4;

    private int minDIstance(float x, float y) {
        Log.i("tags", "x=" + x + "==y=" + y);
        boolean left, top;

        if (x <= (screenWid - x)) {
            left = true;
        } else {
            left = false;
        }
        if (y <= (screenHei - y)) {
            top = true;
        } else {
            top = false;
        }

        if(left&&top){
            if(x<=y){
                return LEFT;
            }else{
                return TOP;
            }
        }
        if(left&&(!top)){
            if(x<=(screenHei-y)){
                return LEFT;
            }else{
                return BOTTOM;
            }
        }

        if((!left)&top){
            if((screenWid-x)<= y){
                return RIGHT;
            }else{
                return TOP;
            }
        }

        if((!left)&(!top)){
            if((screenWid-x)<= (screenHei-y)){
                return RIGHT;
            }else{
                return BOTTOM;
            }
        }
        return 0;

    }

    private void move(float x, float y) {
        int left = (int) (x - width / 2);
        int top = (int) (y - heigh / 2);
        if (left <= 0)
            left = 0;
        if (top <= 0)
            top = 0;

        if (left > screenWid - width)
            left = screenWid - width;
        if (top > screenHei - heigh)
            top = screenHei - heigh;

        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();

        params.setMargins(left, top, (screenWid - left - width), (screenHei- top - heigh));

        view.setLayoutParams(params);
        requestLayout();
    }

    public double getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] results = new float[1];
        Location.distanceBetween(lat1, lon1, lat2, lon2, results);
        return results[0];
    }
}

activity代码

public class MainActivity extends Activity {

    private ImageView dragImg;
    private DragFrameLayout frameLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dragImg = (ImageView) findViewById(R.id.dragImg);
        frameLayout = (DragFrameLayout) findViewById(R.id.becausefloat);
        frameLayout.setDefaultLocation(100, 100);
        frameLayout.setDragImageListener(new DragImageClickListener() {

            private boolean isDaix;

            @Override
            public void onClick() {
                if (isDaix) {
                    dragImg.setBackgroundResource(R.drawable.ic_launcher);
                    isDaix = false;
                } else {
                    dragImg.setBackgroundResource(R.drawable.arrow_down1);
                    isDaix = true;
                }
            }
        });

        frameLayout.setDragImageLocationListener(new DragImageLocationListener() {

            @Override
            public void dragLocation(boolean touchActionUp, float x, float y) {
                // TODO Auto-generated method stub

            }
        });

    }

}

activity的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

        <com.example.dragframelayout.DragFrameLayout
            android:id="@+id/becausefloat"
            android:layout_width="500dp"
            android:layout_height="500dp"
            android:layout_gravity="center_vertical"
            android:background="#ff0000" >

            <ImageView
                android:id="@+id/dragImg"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:background="@drawable/ic_launcher" />
        </com.example.dragframelayout.DragFrameLayout>

</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值