如何导入形状资源(XML),以code?形状、资源、code、XML

2023-09-07 14:06:15 作者:我们不要再相爱了

我一直在试图导入形状的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"
/>

和我的自定义视图code,我尝试从我的外部资源,把它叫做

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);
}

但如果这ruuning在模拟器,它叫错误,因为mDra​​wable应该是GradidentDrawable。但是,并不能使感上的XML code是仅适用于ShapeDrawable。 我不明白为什么它会发生,没有任何人知道为什么会发生?

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?

推荐答案

奇怪的是,&LT;形状&GT; XML资源地图 GradientDrawable ,而 ShapeDrawable 对象是针对有编程方式创建。在一般情况下,我建议你只是铸造绘制对象,除非你需要运行时修改形状参数。

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.