2010-06-18 40 views
3

我一直在尝试导入形状xml到自定义视图。这样,如何将形状资源(xml)导入代码?

<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" 
/> 

,并在我的自定义视图代码中,我试图从我的外部资源

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

但如果这ruuning的模拟器,它叫错误,因为mDrawable应该叫它是“GradidentDrawable”。但是没有意义的是上面的xml代码仅适用于“ShapeDrawable”。 我不明白为什么会发生,有人知道它为什么会发生?

+1

这可能只是一个复制/粘贴错误,但你永远不会关闭你的形状。实际文件末尾是否有? – CaseyB 2010-06-18 03:27:22

+0

这是我的错,而复制/粘贴,谢谢! – tomahawk28 2010-06-20 00:36:48

回答

11

奇怪的是,<shape> XML资源映射到GradientDrawable,而ShapeDrawable对象用于编程创建。一般来说,我建议只铸造到Drawable,除非您需要对形状参数进行运行时修改。

请注意,使用Nine Patch drawable可能更有效,因为一般来说,栅格比矢量具有更好的性能。

+0

谢谢,我按照你的说法将它投射到Drawable,并且它现在起作用。真的很感激它! – tomahawk28 2010-06-24 02:23:26