简体   繁体   中英

Rounded corners in layout with custom color on Android

I've got an xml for the shape and color of my drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/light_red"/>
    <corners android:radius="10dp"/>
</shape>

But I would like to use this drawable as a global one, like having the corners rounded when I'm using it, but being able to change the backgroundColor .

But when I'm trying to change the backgroundColor programatically, it overrides the color like I want but it also override the rounded corners which becomes flat.

For the moment, if I want to have rounded corners with different colors, I need to create multiple XML files with only the android:color changing.

To programmatically change a color globally defined in a shape, use this:

findViewById(R.id.your_xml_element).getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);

Just for other people coming here after, I did some research with what you gave me, this setColorFilter is deprecated since API 29.
I found the solution for non deprecated method (a little bit longer but working):

findViewById(R.id.your_xml_element).getBackground().setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(Color.BLUE, BlendModeCompat.SRC_ATOP));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM