简体   繁体   English

Android 上带有自定义颜色的布局中的圆角

[英]Rounded corners in layout with custom color on Android

I've got an xml for the shape and color of my drawable:我有一个 xml 用于我的可绘制对象的形状颜色

<?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 .但是我想将此可绘制对象用作全局对象,例如在使用它时将角变圆,但能够更改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.但是当我试图以编程方式更改backgroundColor颜色时,它会覆盖我想要的颜色,但它也会覆盖变平的圆角。

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.目前,如果我想用不同的 colors 制作圆角,我需要创建多个 XML 文件,其中只有android:color变化。

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.只是为了之后来这里的其他人,我用你给我的东西做了一些研究,这个setColorFilter自 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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