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

旧时模样 提交于 2019-12-10 23:47:43

问题


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.

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).


回答1:


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.



来源:https://stackoverflow.com/questions/24581900/android-button-background-xml-sometimes-loses-alpha-when-setting-color-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!