以编程方式更改图层列表中形状的颜色 [英] Programmatically change color of shape in layer list

查看:115
本文介绍了以编程方式更改图层列表中形状的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式更改图层列表中形状的颜色(#000000)?

How can I programmatically change the color (#000000) of a shape in a layer list?

这是我的图层列表:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#000000" /> // CHANGE THIS COLOR
        </shape>
    </item>
    <item android:left="5dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/bg" />
        </shape>
    </item>
</layer-list>

推荐答案

首先,您需要为您的layer-list项目分配ID.

First of all you need to assign id to you layer-list item.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- First assign id to the list item-->
    <item  android:id="@+id/your_shape">  
        <shape android:shape="rectangle">
            <solid android:color="#000000" /> 
        </shape>
    </item>
    <item android:left="5dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/bg" />
        </shape>
    </item>
</layer-list>

然后通过ID获取形状.

Then get your shape by id.

LayerDrawable shape = (LayerDrawable) getResources().getDrawable(R.drawable.your_shape)

您可以通过调用更改形状的颜色

And you can change the color of your shape by calling

shape.setColor(Color.Black); // changing to black color

编辑

因为getDrawable()已被弃用.使用以下代码行.

As getDrawable() has been deprecated. Use the following line of code.

LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(YourActivity.this,R.drawable.your_shape)

这篇关于以编程方式更改图层列表中形状的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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