拖动button,不出边界

改进了一下网上查到的拖动button的代码。。。

不会出现超出屏幕的情况。

 DisplayMetrics dm = getResources().getDisplayMetrics();
 final int screenWidth = dm.widthPixels;
 final int screenHeight = dm.heightPixels - 50;
setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnTouchListener(new View.OnTouchListener() {
            int[] temp = new int[]{0, 0};
            public boolean onTouch(View v, MotionEvent event) {
                int eventaction = event.getAction();
                //getRawX()-->屏幕的x坐标
                int x = (int) event.getRawX();
                //getRawY()-->屏幕的y坐标,需要加上标题跟最顶上栏的坐标(50),也就是getRawY()最少就是50
                int y = (int) event.getRawY();
                switch (eventaction) {
                    case MotionEvent.ACTION_DOWN: 
                        //getX()-->控件的x坐标,这里是指按钮的x坐标,
                        // 如果是getY(),则需要减去标题栏和最顶上栏的高度(50左右),
                        temp[0] = (int) event.getX();
                        temp[1] = y - v.getTop();
                        Log.d(TAG, "x->" + x + ", y->" + y + ", v.getTop()->" + v.getTop());
                        Log.d(TAG, "temp[0]->" + temp[0] + ", temp[1]->" + temp[1]);
                        break;
                    case MotionEvent.ACTION_MOVE: 
                        int ll = x - temp[0];
                        int tt = y - temp[1];
                        int rr = x + v.getWidth() - temp[0];
                        int bb = y - temp[1] + v.getHeight();
                        Log.i(TAG, "ll->" + ll + ", rr->" + rr + ", tt->" + tt + ", bb->" + bb + ", temp[0]->" + temp[0] + ", temp[1]->" + temp[1]);
                        if (ll < 0) {
                            ll = 0;
                            rr = v.getWidth();
                        }
                        if (rr > screenWidth) {
                            rr = screenWidth;
                            ll = rr - v.getWidth();
                        }
                        if (tt < 0) {
                            tt = 0;
                            bb = v.getHeight();
                        }
                        if (bb > screenHeight) {
                            bb = screenHeight;
                            tt = bb - v.getHeight();
                        }
                        v.layout(ll, tt, rr, bb);
                        Log.d(TAG, "ll->" + ll + ", rr->" + rr + ", tt->" + tt + ", bb->" + bb + ", temp[0]->" + temp[0] + ", temp[1]->" + temp[1]);
                        v.postInvalidate();
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });

注释的地方注意一下

你可能感兴趣的:(拖动button)