简体   繁体   中英

Show PopUp at the center of anchor(view)

I want to show popup according to anchor position.

Currently it is showing popup at the top left position of anchor, but I want to show this pop up at the center position of anchor instead of left.

Here is my code:

public void show (View anchor) {
    preShow();
    int xPos, yPos,arrowPos;
    mDidAction          = false;
    int[] location      = new int[2];
    anchor.getLocationOnScreen(location);
    Rect anchorRect     = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] 
                        + anchor.getHeight());
    //mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    int rootHeight      = mRootView.getMeasuredHeight();
    if (rootWidth == 0) {
        rootWidth       =  mRootView.getMeasuredWidth();;
    }
    int screenWidth     = mWindowManager.getDefaultDisplay().getWidth();
    int screenHeight    = mWindowManager.getDefaultDisplay().getHeight();

    //automatically get X coord of popup (top left)
    if ((anchorRect.left + rootWidth) > screenWidth) {
        xPos        = anchorRect.left - (rootWidth-anchor.getWidth());          
        xPos        = (xPos < 0) ? 0 : xPos;

        arrowPos    = anchorRect.centerX()-xPos;
    } else {
        if (anchor.getWidth() > rootWidth) {
            xPos = anchorRect.centerX() - (rootWidth/2);
        } else {
            xPos = anchorRect.left;
        }
        arrowPos = anchorRect.centerX()-xPos;
    }
    int dyTop           = anchorRect.top;

    // //automatically get X coord of popup (top left)
    int dyBottom        = screenHeight - anchorRect.bottom;
    boolean onTop       = (dyTop > dyBottom) ? true : false;
    if (onTop) {
        if (rootHeight > dyTop) {
            yPos            = 15;
            LayoutParams l  = mScroller.getLayoutParams();
            l.height        = dyTop - anchor.getHeight();
        } else {
            yPos = anchorRect.top - rootHeight;
        }
    } else {
        yPos = anchorRect.bottom;
        if (rootHeight > dyBottom) { 
            LayoutParams l  = mScroller.getLayoutParams();
            l.height        = dyBottom;
        }
    }

    mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos,yPos);
}

Please suggest

Instead of this

mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos,yPos);

Try this It may help you...

mWindow.showAtLocation(anchor, Gravity.CENTER, 0, 0);

or

mWindow.showAtLocation(anchor, Gravity.CENTER, anchorwidth / 2, anchorheight / 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM