1. 程式人生 > >android控制元件跟隨手勢滑動改變位置

android控制元件跟隨手勢滑動改變位置

    private View.OnTouchListener shopCarSettleTouch = new View.OnTouchListener() {
        int lastX, lastY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int ea = event.getAction();
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int 
screenWidth = dm.widthPixels; // int screenHeight = dm.heightPixels - 100;//需要減掉圖片的高度 int screenHeight = dm.heightPixels;//需要減掉圖片的高度 switch (ea) { case MotionEvent.ACTION_DOWN: lastX = (int) event.getRawX();//獲取觸控事件觸控位置的原始X座標
lastY = (int) event.getRawY(); case MotionEvent.ACTION_MOVE: //event.getRawX();獲得移動的位置 int dx = (int) event.getRawX() - lastX; int dy = (int) event.getRawY() - lastY; int l = v.getLeft() + dx; int
b = v.getBottom() + dy; int r = v.getRight() + dx; int t = v.getTop() + dy; //下面判斷移動是否超出螢幕 if (l < 0) { l = 0; r = l + v.getWidth(); } if (t < 0) { t = 0; b = t + v.getHeight(); } if (r > screenWidth) { r = screenWidth; l = r - v.getWidth(); } if (b > screenHeight) { b = screenHeight; t = b - v.getHeight(); } v.layout(l, t, r, b); Log.e(TAG, "onTouch: " +l+"=="+t+"=="+r+"=="+b); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); v.postInvalidate(); break; case MotionEvent.ACTION_UP: break; } return true; }

};

使用方法:

iv = (ImageView) findViewById(R.id.iv);
iv.setOnTouchListener(shopCarSettleTouch);