0x5453
0x5453

Reputation: 13589

Android: Button background XML sometimes loses alpha when setting color filter

I've run into a really strange issue that might be a bug. I've got a drawable resource that I use as the background for buttons in my app. Here is the XML, pretty simple:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:color="@color/white"
        android:width="5dp" />
    <padding
        android:left="10dp"
        android:right="10dp" />
    <corners android:radius="8dp" />
</shape>

I'm experimenting with letting the user set both the foreground and background colors of the app, so this is how I update the colors:

int foreground = getSharedPreferences("prefs", MODE_PRIVATE).getInt("foreground", 0);
_buttonOptions.setTextColor(foreground);
_buttonOptions.getBackground().setColorFilter(foreground, PorterDuff.Mode.MULTIPLY);

This was working perfectly until a few hours ago. When I ran my app, the drawable gave itself a black background that I can't seem to get rid of.

drawable

I've tried everything I can think of, but the black stays. I didn't even do anything that could have made this happen; the only thing I did around the time that it changed was set the button's text style to bold. I tried changing it back, but that didn't help. Interestingly, I also tried changing the color filter mode to SRC_ATOP, and it colored the entire button area. So it is as if the alpha channel has completely disappeared.

Anyway, I have no clue why this is happening, hence why I think it could be a bug. What do you guys think?

EDIT: The problem only shows up when setting the color filter. If I comment that line out, it works fine (minus the coloring that I need, of course).

Upvotes: 2

Views: 1041

Answers (1)

0x5453
0x5453

Reputation: 13589

Okay, I've fixed the problem. I had to explicitly add a transparent background to the drawable and then clean the project. So the XML now looks like this:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <stroke
        android:color="@color/white"
        android:width="5dp" />
    <padding
        android:left="10dp"
        android:right="10dp" />
    <corners android:radius="8dp" />
</shape>

I tried this earlier, but it didn't do anything because I didn't clean the project, so I assumed that it hadn't worked at all.

Upvotes: 1

Related Questions