Android: How to drag(move) PopupWindow?

泄露秘密 提交于 2019-12-03 14:40:33

In eclipse, when looking at the info on getX(), it says: getX(int) for the first pointer index . I am assuming that this should be the only used when setting the first x and y for ACTION.DOWN. When using ACTION.MOVE, getRawX() and getRawY(), eclipse says: original location of the event on the screen. Using it this way, popup window will not flicker and will remain at its location after moving until it's dismissed.

Updated code:

case MotionEvent.ACTION_DOWN:
    dx = (int) event.getX();
    dy = (int) event.getY();
    break;

case MotionEvent.ACTION_MOVE:
    xp = (int) event.getRawX();
    yp = (int) event.getRawY();
    sides = (xp - dx);
    topBot = (yp - dy);
    popup.update(sides, topBot, -1, -1, true);
    break;

Try this:

mView = mLayoutInflater.inflate(R.layout.popup,
                null);
mPopupWindow = new PopupWindow(mView,
               LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
mPopupWindow.showAtLocation(parentView, Gravity.CENTER, mPosX, mPosY);

mView.setOnTouchListener(new OnTouchListener() {
        private int dx = 0;
        private int dy = 0;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    dx = mPosX - motionEvent.getRawX();
                    dy = mPosY - motionEvent.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mPosX = (int) (motionEvent.getRawX() + dx);
                    mPosY = (int) (motionEvent.getRawY() + dy);
                    pop.update(mPosX, mPosY, -1, -1);
                    break;
            }
            return true;
        }
    });

Try getRawX() and getRawY() instead of getX() and getX(). It still bounces a little bit when you touch it again, but it's much smoother when moving. If you have a better solution please let us know.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!