简体   繁体   English

膨胀图层 - 在android中的形状列表

[英]inflating layer-list of shapes in android

I have the following file in my drawable folder called /drawable/mybkg.xml . 我的drawable文件夹中有以下文件名为/drawable/mybkg.xml I want to inflate it so I can change the colors programmatically. 我想给它充气,这样我就可以通过编程方式更改颜色。 Is that possible in Android? 这可能在Android?

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="oval" >
            <padding
                android:top="5dp"
                android:bottom="2dp"
                android:left="2dp"
                android:right="2dp" />

            <solid
                android:angle="270"
                android:color="#1bd4f6" />

            <stroke
                android:width="2dp"
                android:color="#121ce5" />
        </shape>
    </item>

    <!-- Foreground -->
    <item>
        <shape android:shape="oval" >

            <solid android:color="#1b90f6" />
        </shape>
    </item>

</layer-list>

I just now saw a class called LayerDrawable . 我刚刚看到一个名为LayerDrawable的类。 Does anyone know how I could convert my xml file into such a LayerDrawable either by writing the code or inflating the existing xml? 有谁知道如何通过编写代码或膨胀现有的xml将我的xml文件转换为这样的LayerDrawable

You should use the Resources.getDrawable(int id) method. 您应该使用Resources.getDrawable(int id)方法。 Here is the documentation: http://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int) It inflates any kind of drawable resource. 这是文档: http//developer.android.com/reference/android/content/res/Resources.html#getDrawable(int)它会膨胀任何类型的可绘制资源。 The only thing that is left for you to do is to cast the returned drawable to the most specific type that you need (in your case to LayerDrawable ). 您唯一要做的就是将返回的drawable转换为您需要的最具体类型(在您的情况下为LayerDrawable )。 Here is an example: 这是一个例子:

// calling from Activity
LayerDrawable d = (LayerDrawable) getResources().getDrawable(R.drawable.my_drawable);

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

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