Android PopupWindow elevation does not show shadow

2019-01-14 11:22发布

Android Popwindow does not show shadows when the elevation is set. It appears to support it from the documentation. I am using 5.0 Lollipop.

Creating the popup as follows:

    popupWindow = new PopupWindow(context);
    popupWindow.setOutsideTouchable(true);
    popupWindow.setFocusable(true);
    popupWindow.setElevation(10);
    popupWindow.setContentView(rootView);
    popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY, xPos, yPos);

2条回答
太酷不给撩
2楼-- · 2019-01-14 11:44

For others who visit this answer and missed what the OP already had, you should set the elevation to create a shadow:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    popupWindow.setElevation(20);
}

PopupWindow with shadow

Depending on what your content view is, you might also need to set the background drawable, although this is not always necessary. If needed you can do as @Maragues suggested:

popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

To support pre-Lollipop devices you could use a 9-patch or image that includes the shadow within it.

Code

This is the code for the image above.

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
popupView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        popupWindow.dismiss();
        return true;
    }
});

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    popupWindow.setElevation(20);
}

popupWindow.showAtLocation(anyView, Gravity.CENTER, 0, 0);

Note:

The elevation is in pixels when set in code, but usually in dp when set in xml. You should convert a dp value to pixels when setting it in code.

查看更多
孤傲高冷的网名
3楼-- · 2019-01-14 12:05

As answered by an Android developer.

If the inflated view doesn't have a background set, or the popup window itself doesn't have a background set (or has a transparent background) then you won't get a shadow.

which was my case and seems to be yours, since you are not using setBackgroundDrawable.

This worked for me

popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

I've opened a new issue suggesting that they update the documentation (https://code.google.com/p/android/issues/detail?id=174919)

查看更多
登录 后发表回答