在Android中拖动弹出窗口

时间:2014-03-02 09:42:50

标签: android drag popupwindow dimension

我必须创建一个方形(400dp高度和400dp宽度)的弹出窗口。现在,当我点击位于弹出窗口左上角的按钮时,我想拖动它。我在弹出窗口上的布局上设置onTouch(),这是我用来拖动它的代码:

@Override
public boolean onTouch(View v, MotionEvent event) {
    int eventAction = event.getAction();

    switch (eventAction) {
        case MotionEvent.ACTION_MOVE: // Drag event

            xRow = (int) event.getRawX() - rootView.getWidth();
            yRow = (int) event.getRawY() - rootView.getHeight();             

            /* Updates the position of the popup on the screen */
            update(xRow, yRow, -1, -1);
            break;
    }

    return true;
}

问题是这似乎仅适用于Nexus 7.在10英寸的平板电脑上,它无法正常工作。当我将它拖到较大的平板电脑上时,我的手指和弹出窗口之间有一个空格。所以我假设我使用的测量单位不正确。我试图使用度量标准但没有成功。

1 个答案:

答案 0 :(得分:13)

劳拉,试试这个(把它放在onCreate上):

    final View cv = new View(this);
    setContentView(cv);

    TextView tv = new TextView(this);
    tv.setBackgroundColor(0xffeeeeee);
    tv.setTextColor(0xff000000);
    tv.setTextSize(24);
    tv.setText("click me\nthen drag me");
    tv.setPadding(8, 8, 8, 8);
    mPopup = new PopupWindow(tv, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    OnTouchListener otl = new OnTouchListener() {
        private float mDx;
        private float mDy;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                mDx = mCurrentX - event.getRawX();
                mDy = mCurrentY - event.getRawY();
            } else
            if (action == MotionEvent.ACTION_MOVE) {
                mCurrentX = (int) (event.getRawX() + mDx);
                mCurrentY = (int) (event.getRawY() + mDy);
                mPopup.update(mCurrentX, mCurrentY, -1, -1);
            }
            return true;
        }
    };
    tv.setOnTouchListener(otl);

    mCurrentX = 20;
    mCurrentY = 50;
    cv.post(new Runnable() {
        @Override
        public void run() {
            mPopup.showAtLocation(cv, Gravity.NO_GRAVITY, mCurrentX, mCurrentY);
        }
    });