【问题标题】:Show Android popup window below another view在另一个视图下方显示 Android 弹出窗口
【发布时间】:2020-09-26 06:04:03
【问题描述】:

我正在尝试在另一个视图 (anchorView) 的中心下方显示一个弹出窗口。但我无法使用下面的代码控制位置。

我不知道如何正确使用 showAtLocation。我所理解的似乎 anchorView 参数不起作用。

如何解决问题?

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

【问题讨论】:

    标签: android-popupwindow


    【解决方案1】:

    popup.showAsDropDown(anchorView, 0, 0);
    

    它将弹出到anchorView

    用于添加重力放置

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多