How can I create Drawable (or XmlResourceParser object) from XML source code provided as a string?

1.6k Views Asked by At

How can I create Drawable from XML source code provided as a string?

I found the following method:

Drawable drawable = Drawable.createFromXml();

But it requires to provide XmlResourceParser - and I still don't see a way to create it from XML source code.

Sample of the XML source code:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap
            android:src="@drawable/icon"
            android:gravity="right"
            />
    </item>
</layer-list>
3

There are 3 best solutions below

6
AskNilesh On

FYI

createFromXml()

Create a drawable from an XML document using an optional Resources.Theme.

Try this

public class RecyclerViewActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        Drawable testDrawable;

        Resources res = getResources();
        try {
            testDrawable = Drawable.createFromXml(res, res.getXml(R.xml.test));
        } catch (Exception ex) {
            Log.e("Error", "Exception creating drawable from XML");
        }

    }


}
6
Kit Mak On

I just think of this, maybe not exactly syntactically correct but I believe this is something you want.

public Drawable xmlStringToDrawable(String yourString){
     XmlPullParser parser = Xml.newPullParser();
     parser.setInput(new StringReader(yourString));
     return Drawable.createFromXml(getResources(),parser)
}
0
Dmitry On

This is not an answer to the question. But it solved my problem. Thanks everyone for the help:

        Drawable icon = resources.getDrawable(resources.obtainTypedArray(R.array.arrayName).getResourceId(index, 0), context.getTheme());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
        bitmapDrawable.setGravity(Gravity.RIGHT);

I generate only index on run-time in this approach.