Here's how I create a 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
is a solid color, white or black, depending on the theme. Sometimes following happens:
How can I avoid this? It happens in the emulator with android 6 SOMETIMES only for example... Normally, the PopupWindow
background works as expected though...
Edit
Additionally, here's my getThemeReference
method:
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;
}
}
EDIT 2 - this may solve the problem: using getThemeColor
instead of 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;
}
}
Thanks for the update, I asked you to show the method because I actually use the same kind of thing in my apps to retrieve color attributes, but our methods are a bit different.
Here is mine:
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;
}
Even though I can't be sure it is indeed the problem, there is something wrong with your comments. The call new ColorDrawable()
is expecting a color, not a reference. I sometimes also did this mistake in the past and also got weird colors, because the system was trying to generate a color with a reference ID. Have you tried a real color like red to see if your method really works?
I would replace anyway your method with mine because it guarantees you to retrieve a color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With