使用 BitmapDrawable 弃用方法的自定义 PopupWindow

Custom PopupWindow with BitmapDrawable deprecated method

在我使用自定义 PopupWindow 的应用程序中,我正在使用

popup.setBackgroundDrawable(new BitmapDrawable());

方法。现在这里已弃用,如果没有这种方法,我将无法为我的弹出窗口提供背景。我从文章中读到它的替代方案是

popup.setsetBackgroundDrawable(new BitmapDrawable(Context.Resources,Drawable);

但在这里我没有为我的弹出窗口使用任何可绘制对象。我的代码在下面给出了我正在制作自定义 Popupwindow 的地方,这里是为了解决这个问题。

@Override
    public void onWindowFocusChanged(boolean hasFocus) {

        int[] location = new int[2];
        Button button = (Button) findViewById(R.id.VBG_img_pin_x);

        // Get the x, y location and store it in the location[] array
        // location[0] = x, location[1] = y.
        button.getLocationOnScreen(location);

        // Initialize the Point with x, and y positions
        p = new Point();
        p.x = location[0];
        p.y = location[1];
    }

    // The method that displays the popup.
    private void showPopup(final Activity context, Point p) {

//      Display display = getWindowManager().getDefaultDisplay();

        DisplayMetrics display = this.getResources().getDisplayMetrics();

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

//      int width = display.getWidth(); // deprecated
//      int height = display.getHeight(); // deprecated

        int popupWidth = width / 2;
        int popupHeight = height;

        ChatUtils.getScreenHeight(getBaseContext());

        // Inflate the popup_layout.xml
        LinearLayout viewGroup = (LinearLayout) context
                .findViewById(R.id.popup);

        LayoutInflater layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

        onSetAlpha(240, layout);
//      layout.setAlpha((float) 0.95);

        // Creating the PopupWindow
        final PopupWindow popup = new PopupWindow(context);

        popup.setTouchable(true);
        popup.setFocusable(false);
        popup.setOutsideTouchable(true);
        popup.setContentView(layout);
        popup.setWidth(popupWidth);
        popup.setHeight(popupHeight);
        popup.setFocusable(true);

        // Some offset to align the popup a bit to the right, and a bit down,
        // relative to button's position.
        // Clear the default translucent background
        popup.setBackgroundDrawable(new BitmapDrawable());

}

如果要清理背景,如您的评论所述

//Clear the default translucent background

你可以使用

popup.setBackgroundDrawable(null);

如果要为背景着色,请使用此选项

 popup.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));

这没有被弃用。