Android PopupWindow - 如何为具有屏幕按钮的设备获得相同的底部边距

时间:2016-12-15 13:57:39

标签: android popupwindow

我在不同设备上存在底部边距问题。 如何使用/不使用屏幕按钮获得相同的底部边距?

PopupWindow的实现:

DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;
        int height = dm.heightPixels;

        View viewGroup= activity.getLayoutInflater().inflate(R.layout.my_dialog, null, false);

        popupWindow = new PopupWindow(viewGroup, width, height);

Nexus 6

enter image description here

三星5

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#AA000000"
    >


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="15dp"
        android:background="#fff"
        android:layout_weight="1">

        ...


    </LinearLayout>

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

从layout_height中删除match_parent并将其替换为wrap_content,如下所示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#AA000000">


<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:layout_margin="15dp"
    android:orientation="vertical"
    android:background="#fff"
    android:layout_weight="1">

    ...


</LinearLayout>

答案 1 :(得分:0)

这是一个解决方案:

if (hasNavBar(activity.getResources())){
    LinearLayout linearLayout = (LinearLayout) popupWindow.getContentView().findViewById(R.id.linear_layout_dialog);
    if( linearLayout.getLayoutParams() instanceof ViewGroup.MarginLayoutParams)
    {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) linearLayout.getLayoutParams();

        lp.bottomMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            (float) 43, activity.getResources().getDisplayMetrics());

        linearLayout.setLayoutParams(lp);

    }

}

public static boolean hasNavBar (Resources resources)
    {
        int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        return id > 0 && resources.getBoolean(id);
    }