我有一部android 4.0手机,比如a,还有一部4.4平板电脑,都有一个软件导航栏。
我用这个:

showAtLocation(myView, Gravity.NO_GRAVITY, x, y);

在特定位置显示窗口。实际结果是,在A上看起来不错,但在B上有一个Y偏移量。我发现偏移量似乎与B的导航栏高度相同。所以我用下面的代码计算高度并做减法运算:
private int getNavigationBarHeight(Resources res, Context context) {
        final int apiLevel = Build.VERSION.SDK_INT;
        if((apiLevel >= Build.VERSION_CODES.HONEYCOMB && apiLevel <= Build.VERSION_CODES.HONEYCOMB_MR2)
                ||
                (apiLevel >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && !ViewConfiguration.get(context).hasPermanentMenuKey())
                ) {
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                return res.getDimensionPixelSize(resourceId);
            }
        }
        return 0;
    }

新的结果是:窗口现在在B中是正常的,但是当在A中显示时,它有一个Y偏移。
问题是,如何使我的窗口在两个设备上都显示为正常

最佳答案

今天我和你有同样的问题。在我的模拟器上,由于PopupWindows的Gravity.NO_GRAVITY,PopupWindows被正确地绘制在窗口的边界内。然而,在我的Nexus7平板电脑上,弹出窗口显示在设备状态栏的下方,该栏显示在底部。
当我点击屏幕上的ImageButtons,在ImageButtons的Y位置(和宽度)时,弹出窗口就会出现。这个imagebutton的位置可能在窗口的边界内,或者刚好/完全在平板电脑的底部状态栏下面。
这就是我想到的:
我们所拥有的:
我们给PopupWindow的ShowAtLocation方法指定的[x,y]-位置(这里只需要y-位置,我将其命名为match_parent
我们的计算:
弹出窗口高度
状态栏高度
窗口边界内的最大可能高度(oldY
然后我们检查:
我们检查screenHeight - statusBarHeight - popupHeight是否大于oldY
如果是这种情况,maxY将是newY并且我们重新绘制弹出窗口。如果不是这样,那就意味着我们什么都不做,只使用maxY作为正确的y位置。
注1:我为此编写了代码,但在调试过程中发现,模拟器和Nexus平板电脑上的状态栏高度都为0,因此仅使用oldY就足够了。不过,我在我的配置文件中包含了计算底部状态栏高度的代码,其中包含一个布尔值以启用/禁用此功能,以防将来应用程序安装在另一台平板电脑上。
在代码中,我只是添加了上面的描述,以明确我用来解决此问题的方法:

// Get the [x, y]-location of the ImageButton
int[] loc = new int[2];
myImageButton.getLocationOnScreen(loc);

// Inflate the popup.xml
LinearLayout viewGroup = (LinearLayout)findViewById(R.id.popup_layout);
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(R.layout.popup, viewGroup);

// Create the PopupWindow
myPopupWindow = new PopupWindow(ChecklistActivity.this);
myPopupWindow.setContentView(layout);
myPopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

... // Some more stuff with the PopupWindow's content

// Clear the default translucent background and use a white background instead
myPopupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));

// Displaying the Pop-up at the specified location
myPopupWindow.showAtLocation(layout, Gravity.NO_GRAVITY, 0, loc[1]);

// Because the PopupWindow is displayed below the Status Bar on some Device's,
// we recalculate it's height:
// Wait until the PopupWindow is done loading by using an OnGlobalLayoutListener:
final int[] finalLoc = loc;
if(layout.getViewTreeObserver().isAlive()){
    layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        // This will be called once the layout is finished, prior to displaying it
        // So we can change the y-position of the PopupWindow just before that
        @Override
        public void onGlobalLayout() {
            // Get the PopupWindow's height
            int popupHeight = layout.getHeight();
            // Get the Status Bar's height
            int statusBarHeight = 0;
            // Enable/Disable this in the Config-file
            // This isn't needed for the Emulator, nor the Nexus 7 tablet
            // Since the calculated Status Bar Height is 0 with both of them
            // and the PopupWindow is displayed at its correct position
            if(D.WITH_STATUS_BAR_CHECK){
                // Check whether the Status bar is at the top or bottom
                Rect r = new Rect();
                Window w = ChecklistActivity.this.getWindow();
                w.getDecorView().getWindowVisibleDisplayFrame(r);
                int barHeightCheck = r.top;
                // If the barHeightCheck is 0, it means our Status Bar is
                // displayed at the bottom and we need to get it's height
                // (If the Status Bar is displayed at the top, we use 0 as Status Bar Height)
                if(barHeightCheck == 0){
                    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                    if (resourceId > 0)
                        statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                }
            }
            // Get the Screen's height:
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenHeight = dm.heightPixels;
            // Get the old Y-position
            int oldY = finalLoc[1];
            // Get the max Y-position to be within Window boundaries
            int maxY = screenHeight - statusBarHeight - popupHeight;
            // Check if the old Y-position is outside the Window boundary
            if(oldY > maxY){
                // If it is, use the max Y-position as new Y-position,
                // and re-draw the PopupWindow
                myPopupWindow.dismiss();
                myPopupWindow.showAtLocation(layout, Gravity.NO_GRAVITY, 0, maxY);
            }

            // Since we don't want onGlobalLayout to continue forever, we remove the Listener here again
            layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
}

注2:我已将此行的screenHeight - popupHeight本身设置为tag_popup
myPopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

弹出窗口的主布局为:
 <?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE xml>
 <!-- The DOCTYPE above is added to get rid of the following warning:
     "No grammar constraints (DTD or XML schema) detected for the document." -->

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/popup_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@layout/tag_shape"
     android:padding="@dimen/default_margin">

     ... <!-- Popup's Content (EditTexts, Spinner, TextViews, Button, etc.) -->

 </RelativeLayout>

注3:我的应用程序被迫保持纵向模式。我还没有在横向模式下测试,但我认为应该做一些修改(尽管不确定)。编辑:经过测试,它也可以在我的两台设备上以横向模式工作。我不知道这是否也适用于启用底部栏高度的横向模式。
希望这能帮助你和其他有类似问题的人。希望他们能在将来修复popuppwindows的width = match_parent; height = wrap_content,所以它永远不会低于状态栏,除非程序员自己想要并更改popuppwindows的设置。

10-07 13:07