【问题标题】:How to import shape resource(xml) to code?如何将形状资源(xml)导入代码?
【发布时间】:2010-06-18 02:34:23
【问题描述】:

我一直在尝试将形状 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);
}

但是如果在模拟器上运行,它会调用错误,因为 mDrawable 应该是“GradientDrawable”。但没有意义的是上面的 xml 代码仅适用于“ShapeDrawable”。 我不明白为什么会这样,有人知道为什么会这样吗?

【问题讨论】:

  • 这可能只是一个复制/粘贴错误,但你永远不会关闭你的形状。实际文件的末尾是否有 ?
  • 复制粘贴是我的错,谢谢!

标签: xml android


【解决方案1】:

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

请注意,使用九个可绘制对象可能更有效,因为通常光栅比矢量具有更好的性能。

【讨论】:

  • 谢谢,我按照你说的将它转换为 Drawable,现在它可以工作了。真的很感激!
猜你喜欢
  • 2016-08-09
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 2015-04-17
  • 2014-07-08
相关资源
最近更新 更多