Show Android popup window below another view

598 Views Asked by At

I am trying to show a popup right below the center of another view (anchorView). But I cannot control the location using the code below.

I don't know how to use showAtLocation correctly. It seems the anchorView paramter does not function in the way I understand.

How to fix the problem?

    TextView  clickMe = findViewById(R.id.click_me) ;
    clickMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            displayPopupWindow(getApplicationContext(), R.layout.sn_chat_click_menu, findViewById(R.id.parm_display) ) ;

        }
    });



 private void displayPopupWindow(Context mContext, int layoutResId, View anchorView ) {
        PopupWindow popup = new PopupWindow(mContext);
        View layout = getLayoutInflater().inflate(layoutResId, null);
        popup.setContentView(layout);
        // Set content width and height
        popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        popup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        // Closes the popup window when touch outside of it - when looses focus
        popup.setOutsideTouchable(true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new BitmapDrawable());
        // Show related to anchorView

        Rect  anchorRect = locateViewRect(anchorView) ;
        int x = (anchorRect.right-anchorRect.left) / 2 ; 
        int y = (anchorRect.bottom-anchorRect.top) / 2 ; 
        popup.showAtLocation(anchorView, Gravity.NO_GRAVITY, x,y);
    }

    public Rect locateViewRect(View v)
    {
        int[] loc_int = new int[2];
        if (v == null) return null;
        try {
            v.getLocationOnScreen(loc_int);
        } catch (NullPointerException npe) {
            //Happens when the view doesn't exist on screen anymore.
            return null;
        }
        Rect location = new Rect();
        location.left = loc_int[0];
        location.top = loc_int[1];
        location.right = location.left + v.getWidth();
        location.bottom = location.top + v.getHeight();
        return location;
    }
1

There are 1 best solutions below

0
On

Put

popup.showAsDropDown(anchorView, 0, 0);

It will make the pop up down to the anchorView

For adding gravity put

popup.showAsDropDown(anchorView, 0, 0,Gravity.NO_GRAVITY);