访问在theme和attrs.xml android中定义的资源

Sha*_*dul 34 resources android attributes themes drawable

我有一个场景,我想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自定义的自定义Theme.

小智 71

我想你可以用这段代码得到Drawable:

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();
Run Code Online (Sandbox Code Playgroud)

  • 它很吵闹,但你应该调用a.recycle(); 你做完之后 此外,obtainStyledAttributes中的第一个参数是可选的. (4认同)
  • 好吧,这可能会更简化:只是`Drawable drawable = a.getDrawable(0);`就够了(其中0是new int []数组中requeired属性的索引). (4认同)

and*_*per 11

另一种可能的方法:

  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;
    }
Run Code Online (Sandbox Code Playgroud)

这里不需要回收任何东西......

用法:

@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
}
Run Code Online (Sandbox Code Playgroud)