Access resource defined in theme and attrs.xml android

前端 未结 5 1957
情歌与酒
情歌与酒 2020-12-04 21:55

I have a scenario in which I want to set a Drawable depending upon the theme defined.

To explain this further, Here is what I have in code:

5条回答
  •  渐次进展
    2020-12-04 22:47

    Another possible way to do it:

      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;
        }
    

    Or in Kotlin:

    @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
    }
    

    no need to recycle anything here...

    usage:

    int drawableResId=getResIdFromAttribute(this,R.attr.homeIcon);
    Drawable drawable = getResources().getDrawable(drawableResId);
    

提交回复
热议问题