Saturday, April 7, 2012

Load Android Drawable from XML

  • Create an XML file in res/xml with the Drawable. Assume the below to be my_drawable.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape 
       xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid
            android:color="#FF555599" />
        <stroke
            android:width="2dp"
            android:color="#FF000000"
            android:dashWidth="2dp"
            android:dashGap="1dp" />
    </shape>

  • Load the Drawable in code

    Drawable myDrawable;
    Resources res = getResources();
    try {
       myDrawable = Drawable.createFromXml(res, res.getXml(R.xml.my_drawable));
    catch (Exception ex) {
       Log.e("Error", "Exception loading drawable");
    }

  • Use the Drawable.

    @Override
    public void onDraw(Canvas canvas) {
       if (null != myDrawable) {
          myDrawable.setBounds(0, 0, getWidth(), getHeight());
          myDrawable.draw(canvas);
       }
    }

No comments:

Post a Comment