Set theme color dynamically

后端 未结 5 1429
北荒
北荒 2020-12-14 23:31

I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):



        
5条回答
  •  自闭症患者
    2020-12-15 00:01

    If I understand corectly you're looking for a way to

    1. extract a style from a theme,
    2. extract a value (text color) from said style.

    Let's get to it.

    // Extract ?my_item_style from a context/activity.
    final TypedArray a = context.obtainStyledAttributes(new int[] { R.attr.my_item_style });
    @StyleRes final int styleResId = a.getResourceId(0, 0);
    a.recycle();
    
    // Extract values from ?my_item_style.
    final TypedArray b = context.obtainStyledAttributes(styleResId, new int[] { android.R.attr.textColor });
    final ColorStateList textColors = b.getColorStateList(0);
    b.recycle();
    
    // Apply extracted values.
    if (textColors != null) {
        textView.setTextColor(textColors);
    }
    

    A couple of notes:

    1. TypedArray does not support getting support vector drawables and theme references in color state lists on older API levels. If you're willing to use AppCompat internal API you may want to try TintTypedArray.
    2. Allocating int[] all the time is costly, make it a static final.
    3. If you want to resolve multiple attributes at once the array of attributes has to be sorted! Else it crashes sometimes. generates such array and corresponding indices for you.

提交回复
热议问题