1. 程式人生 > >Android 自定義可拖拽View,界面渲染刷新後不會自動回到起始位置

Android 自定義可拖拽View,界面渲染刷新後不會自動回到起始位置

AD att starty attrs floating blog body .get dmi

以自定義ImageView為例:

/**
 * 可拖拽ImageView
 * Created by admin on 2017/2/21.
 */
public class FloatingImageView extends ImageView{


    public FloatingImageView(Context context) {
        super(context);
    }

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

    public FloatingImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP
) public FloatingImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } int startX; int startY; int left; int top; int[] temp = new int[]{ 0, 0 }; @Override public boolean onTouchEvent(MotionEvent event) { boolean isMove = false; int x = (int) event.getRawX(); int y = (int) event.getRawY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN
: // touch down so check if the startX = x; startY = y; temp[0] = (int) event.getX(); temp[1] = y - getTop(); break; case MotionEvent.ACTION_MOVE: // touch drag with the ball left = x - temp[0]; top = y - temp[1]; if(left < 0){//控制左邊界不超出 left = 0; } layout(left, top, left + getWidth(),top + getHeight());//自由拖拽 break; case MotionEvent.ACTION_UP
: if (Math.abs(x - startX) > 2 || Math.abs(y - startY) > 2){//判斷是否移動,再一定範圍內不算是移動,解決觸發事件沖突 //將最後拖拽的位置定下來,否則頁面刷新渲染後按鈕會自動回到初始位置 //註意父容器 RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams(); lp.setMargins(left, top,0,0); setLayoutParams(lp); //確定是拖拽 isMove = true; } break; } return isMove ? true : super.onTouchEvent(event); } }

Android 自定義可拖拽View,界面渲染刷新後不會自動回到起始位置