为什么android popupwindow showAsDropDown offsetx无效?

时间:2015-03-31 19:31:28

标签: android android-layout mobile

popupWindow.showAsDropDown(morebutton, xOffset, yOffset);

无论xOffset的值如何,弹出窗口都在屏幕右侧

final PopupWindow popupWindow = new PopupWindow(DashboardActivity.applicationContext);
                        LayoutInflater inflater = (LayoutInflater) DashboardActivity.applicationContext.getSystemService(
                                Context.LAYOUT_INFLATER_SERVICE);
popupWindow.setFocusable(true);
                        popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
                        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
                        popupWindow.setContentView(view);
                        popupWindow.setBackgroundDrawable(new ColorDrawable(
                                android.graphics.Color.TRANSPARENT));
popupWindow.showAsDropDown(morebutton, **-220**, -40);

无论我设置值offsetX,他都在屏幕右侧显示

1 个答案:

答案 0 :(得分:5)

默认情况下,

PopupWindow会尝试将您的contentViewanchor Gravity.TOP | Gravity.START(左上角)对齐。如果您的contentView没有剩余空间,那么它会偏移以适应屏幕,这可能就是它保持在右侧的原因。

以下xOffset会将contentViewanchor的右上角对齐:

view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int xOffset = -(view.getMeasuredWidth() - morebutton.getWidth());

popupWindow.showAsDropDown(morebutton, xOffset, 0);

您可能需要以下内容:

popupWindow.showAsDropDown(morebutton, xOffset - 220, -40);