获取自定义主题(attr.xml)中的定义的图片(Drawable)

来源:互联网 发布:网络数据传输流程 编辑:程序博客网 时间:2024/06/05 03:27

  获取自定义主题(attr.xml)中的定义的图片(Drawable)

从事安卓开发一周学到了很多东西。一个刚刚从学校毕业的菜鸟想要变成编程达人注定不是一条容易的路。争取每天写下一点工作心得或者收获。


正文:

今天在开发中需要解决一个根据当前主题Theme而变换图片的需求。 想必大家都会如何从layout设置。如下

attrs.xml

<resources>    <declare-styleable name="MyTheme">        <attr name="homeyjzc" format="reference" />  //index=1        <attr name="homessgj" format="reference" />  //index=1    </declare-styleable></resources>


attrs.xml中定义了两个引用类型,其指向了Styles.xml定义的Theme。


Styles.xml

    <style name="Theme3" parent="AppTheme.NoActionBar">        <item name="homessgj">@drawable/home_ssgj1</item>        <item name="homeyjzc">@drawable/home_spjd1</item>    </style>


重点来了:如何使用相应的图片呢?

分为两种情况:

1. layout中使用,这种情况相对简单。

android:background="?titlebg"
加上一个"?" 即可指向当前Theme中的图片


2. .java文件中使用则相对麻烦一点

TypedArray a = context.obtainStyledAttributes(R.styleable.MyTheme);Drawable d = a.getDrawable(iconId); //icoid 指的是所需要的drwable在Mytheme的实际index        // 回收a.recycle();


错误方法:

Drawable d = a.getDrawable(R.attr.homeyjzc); //此处并不能指向homeyjzc代表的Drawable


完成

总结:期初作者没有使用styleable,而是将"reference"直接放入attr.xml文件中,在layout中使用完全没有问题,直接调用。但是java文件中总是报错,obtainStyledAttributes()方法只适用于读取styleable中定义的attribute。
不知道各位大神有没有其他能够获取自定义style中所指向的drawable?
0 0
原创粉丝点击