PopupWindow的背景有时会变成透明和紫色。

7
这是我创建 PopupWindow 的方法:
private static PopupWindow createPopup(FragmentActivity activity, View view)
{
    PopupWindow popup = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
    popup.setOutsideTouchable(true);
    popup.setFocusable(true);
    popup.setBackgroundDrawable(new ColorDrawable(Tools.getThemeReference(activity, R.attr.main_background_color)));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        popup.setElevation(Tools.convertDpToPixel(8, activity));
    PopupWindowCompat.setOverlapAnchor(popup, true);

    return popup;
}
main_background_color是一个实心颜色,根据主题而定,通常为白色或黑色。有时会出现以下情况: enter image description here 如何避免这种情况?例如在模拟器上只有安卓6有时才会发生... 通常,PopupWindow背景的工作都正常... 编辑 此外,这是我的getThemeReference方法:
public static int getThemeReference(Context context, int attribute)
{
    TypedValue typeValue = new TypedValue();
    context.getTheme().resolveAttribute(attribute, typeValue, false);
    if (typeValue.type == TypedValue.TYPE_REFERENCE)
    {
        int ref = typeValue.data;
        return ref;
    }
    else
    {
        return -1;
    }
}

编辑2 - 这可能解决问题:使用getThemeColor而不是getThemeReference

public static int getThemeColor(Context context, int attribute)
{
    TypedValue typeValue = new TypedValue();
    context.getTheme().resolveAttribute(attribute, typeValue, true);
    if (typeValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typeValue.type <= TypedValue.TYPE_LAST_COLOR_INT)
    {
        int color = typeValue.data;
        return color;
    }
    else
    {
        return -1;
    }
}

请发布您的 getThemeReference 方法。 - Yoann Hercouet
完成。但我不相信问题的原因在那里,因为这意味着这个问题总是会发生,但它只是偶尔发生(直到现在,我只在Android 6上看到过它)。 - prom85
1个回答

5
感谢您的更新,我要求您展示这种方法是因为我在我的应用程序中实际上使用了类似的东西来获取颜色属性,但我们的方法有些不同。
以下是我的方法:
public static int getThemeColor(Context context, int attributeId) {
    TypedValue typedValue = new TypedValue();

    TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[] { attributeId });
    int color = a.getColor(0, 0);

    a.recycle();

    return color;
}

尽管我不能确定这是否是问题所在,但你的评论出了点问题。调用new ColorDrawable()期望的是一个颜色,而不是一个引用。我过去有时也会犯这个错误,因为系统会尝试使用引用ID生成一种颜色,导致出现奇怪的颜色。你尝试过像红色这样的真正颜色来验证你的方法是否有效吗?
总之,我建议用我的方法替换你的方法,因为它保证可以检索到一种颜色。

你认为(我可能做错了,这是真的),使用我的方法,同一设备和系统会创建不同的颜色吗?这种情况发生在运行我的应用程序时。你打开弹出窗口,它很好,你旋转设备,重新打开弹出窗口,它变成紫色(它会不可预测地改变颜色,大多数时间颜色是正确的)。 - prom85
顺便说一下,我的 R.attr.main_background_color 是一个引用...它不是颜色...我有第二个方法,与你的方法同名 ;-). 它应该也能工作,我也在我的问题中发布了它...这可能真的是因为我传递了一个颜色引用而不是完全解析的颜色... - prom85
@prom85 正如我所说,不确定是否会有任何区别,但值得一试。在您提供的其余代码中,我没有看到其他可能与此问题相关的内容。 - Yoann Hercouet
至少,ColorDrawable 需要一个颜色而不是引用的提示仍然是正确的,所以这可能是问题所在... 我会尝试一下并查看问题是否在之后消失了 - prom85
到目前为止,这似乎真的解决了问题。 - prom85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接