我有一个场景,其中我想根据定义的主题设置一个Drawable。
为了进一步解释这一点,下面是我在代码中的内容:
\res\values\attrs.xml
<resources>
<declare-styleable name="AppTheme">
<attr name="homeIcon" format="reference" />
</declare-styleable>
</resources>res\values\styles.xml
<resources>
<style name="AppTheme" parent="android:style/Theme">
<item name="attr/homeIcon">@drawable/ic_home</item>
</style>
</resources>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>因此,正如您注意到的,我正在定义一个定制的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" />并将Drawable ic_home呈现在ImageView中。
但我无法理解如何以编程方式访问Drawable。
我试图通过定义holder 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>汇总I希望以编程方式访问自定义
Theme中定义的Drawable。
发布于 2012-01-09 19:37:36
我认为您可以通过以下代码获得绘图:
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});
int attributeResourceId = a.getResourceId(0, 0);
Drawable drawable = getResources().getDrawable(attributeResourceId);
a.recycle();发布于 2014-11-19 15:34:46
另一种可能的方法是:
public static int getResIdFromAttribute(final Activity activity,final int attr) {
if(attr==0)
return 0;
final TypedValue typedvalueattr=new TypedValue();
activity.getTheme().resolveAttribute(attr,typedvalueattr,true);
return typedvalueattr.resourceId;
}或者在科特林:
@JvmStatic
fun getResIdFromAttribute(activity: Activity, attr: Int): Int {
if (attr == 0)
return 0
val typedValue = TypedValue()
activity.theme.resolveAttribute(attr, typedValue, true)
return typedValue.resourceId
}这里不需要回收任何东西..。
用法:
int drawableResId=getResIdFromAttribute(this,R.attr.homeIcon);
Drawable drawable = getResources().getDrawable(drawableResId);发布于 2015-12-30 17:36:11
我使用下面的方法获取资源id表单样式属性。然后,它可以用于可绘制,字符串,尺寸等。
TypedArray typedArray = context.getTheme().obtainStyledAttributes(new int[] { R.attr.attrName });
int resourceId = typedArray.getResourceId(0, defaultResourceId);
typedArray.recycle();干杯:-)
https://stackoverflow.com/questions/8793183
复制相似问题