Question

I had to create a popup window which is a square (400dp height and 400dp width). Now I want to drag it when I tap a button which is positioned on the top left of the popup. I set onTouch() on the layout which is placed on the popup and this is the code I use in order to drag it:

@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;
}

The problem is that this seems to work only for Nexus 7. On a tablet of 10 inch, it is not working properly. When I drag it on the larger tablet, there is a space between my finger and popup. So I assume that the units of measurement I use are not the right ones. I have tried to use the Metrics but no success.

Was it helpful?

Solution

Laura, try this (place it in 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);
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top