我有一个场景,我想Drawable根据定义的主题设置一个.
为了进一步解释这一点,以下是我在代码中的内容:
\ RES \值\ attrs.xml
<resources>
<declare-styleable name="AppTheme">
<attr name="homeIcon" format="reference" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
水库\值\ styles.xml
<resources>
<style name="AppTheme" parent="android:style/Theme">
<item name="attr/homeIcon">@drawable/ic_home</item>
</style>
</resources>
Run Code Online (Sandbox Code Playgroud)
AndroidManifest.xml中
<application android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Run Code Online (Sandbox Code Playgroud)
因此,您已经注意到我正在定义自定义attr homeIcon并在AppTheme中设置属性值.
当我在布局XML中定义此属性并尝试访问它时,它可以顺利运行
<ImageView android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="?attr/homeIcon" />
Run Code Online (Sandbox Code Playgroud)
并将Drawableic_home 呈现为ImageView.
但我无法弄清楚如何以Drawable编程方式访问.
我尝试通过定义持有者来解决LayerList Drawable这个问题,导致资源未找到异常:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="?attr/homeIcon" />
</layer-list>
Run Code Online (Sandbox Code Playgroud)
总结 我想以编程方式访问
Drawable …