Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import shape resource(xml) to code?

Tags:

android

xml

I've been trying to import shape xml to customized View. like this,

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid 
  android:color="#f0600000"/>
<stroke
  android:width="10dp" 
  android:color="#00FF00"/>
<corners 
  android:radius="15dp" />
<padding 
  android:left="10dp"
  android:top="10dp"
  android:right="10dp"
  android:bottom="10dp"
/>

and in my customized view code, I try to call it from my external resources

    private void initTestView(){
    Resources res = this.getResources();
    mDrawable = (ShapeDrawable)res.getDrawable(R.drawable.recshape);
}

but if this ruuning on emulator, it called error because mDrawable should be "GradidentDrawable". but what doesn't make it sense is the upper xml code is only for "ShapeDrawable". I don't understand why it happen, does anybody know why it happen?

like image 237
tomahawk28 Avatar asked Jun 18 '10 02:06

tomahawk28


1 Answers

Strangely enough, <shape> XML resources map to GradientDrawable, whereas ShapeDrawable objects are there for programmatic creation. In general, I'd recommend just casting to Drawable, unless you need to make runtime modifications to the shape parameters.

Note that it may be more efficient to use Nine Patch drawables instead, because in general, raster has better performance than vector.

like image 176
Roman Nurik Avatar answered Oct 12 '22 11:10

Roman Nurik