如何将颜色值动态传递给xml [英] How to pass the color value dynamically to xml

查看:52
本文介绍了如何将颜色值动态传递给xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个会绘制椭圆形的xml,代码如下:

i have a xml which will draw oval shape , the code is below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#61118"/>
    <stroke android:width="1sp" android:color="#1B434D" />
</shape>

现在我在这里 android:color =#61118 我需要传递java类中的值,有可能吗?

Now i here android:color="#61118" i need to pass the value from java class, Is it possible?

如果没有其他替代方法?

If not is there any alternative way?

推荐答案

不幸的是,您无法将参数传递给XML Drawables。

Sadly you cannot pass arguments to XML Drawables.

如果您没有太多不同的值,您可以使用 < level-list> 并提供您的形状的不同版本。

If you don't have too many different values, you can use a <level-list> and provide different versions of your shape.

然后,您将使用 Drawable.setLevel(int)

Then you would change the level associated with your drawable to change the color using Drawable.setLevel(int).

my_drawable.xml

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0">
        <shape android:shape="oval">
            <solid android:color="@color/red"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="1">
        <shape android:shape="oval">
            <solid android:color="@color/green"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="2">
        <shape android:shape="oval">
            <solid android:color="@color/blue"/>
            <stroke android:width="1sp" android:color="@color/blue" />
        </shape>
    </item>
</level-list>

MyActivity.java

// myView is a View (or a subclass of View) 
// with background set to R.drawable.my_drawable
myView.getBackground().setLevel(0); // Set color to red
myView.getBackground().setLevel(1); // Set color to green
myView.getBackground().setLevel(2); // Set color to blue

// myImageView is an ImageView with its source
// set to R.drawable.my_drawable
myImageView.setImageLevel(0); // Set color to red
myImageView.setImageLevel(1); // Set color to green
myImageView.setImageLevel(2); // Set color to blue

这篇关于如何将颜色值动态传递给xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆