Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inflating layer-list of shapes in android

I have the following file in my drawable folder called /drawable/mybkg.xml. I want to inflate it so I can change the colors programmatically. Is that possible in 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. Does anyone know how I could convert my xml file into such a LayerDrawable either by writing the code or inflating the existing xml?

like image 413
Cote Mounyo Avatar asked Aug 03 '13 12:08

Cote Mounyo


1 Answers

You should use the Resources.getDrawable(int id) method. Here is the documentation: http://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int) It inflates any kind of drawable resource. 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). Here is an example:

// calling from Activity
LayerDrawable d = (LayerDrawable) getResources().getDrawable(R.drawable.my_drawable);
like image 88
GareginSargsyan Avatar answered Nov 15 '22 03:11

GareginSargsyan