Android 自訂可拖拽View,介面渲染重新整理後不會自動回到起始位置

來源:互聯網
上載者:User

標籤:margin   case   範圍   drag   控制   事件衝突   getheight   getrawx   pre   

以自訂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,介面渲染重新整理後不會自動回到起始位置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.