Get attr color value based on current set theme

后端 未结 1 1990
谎友^
谎友^ 2021-01-18 01:45

In my activity I\'m maintaining a SuperActivity, in which I\'m setting the theme.

public class SuperActivity extends Activity {
@Override
    pr         


        
相关标签:
1条回答
  • 2021-01-18 01:58

    You have two possible solutions (one is what you actually have but I include both for the sake of completeness):

    TypedValue typedValue = new TypedValue();
    if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true))
      return typedValue.data;
    else
      return Color.TRANSPARENT;
    

    or

    int[] attribute = new int[] { R.attr.xxx };
    TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
    int color = array.getColor(0, Color.TRANSPARENT);
    array.recycle();
    return color;
    

    Color.TRANSPARENT could be any other default for sure. And yes, as you suspected, the context is very important. If you keep getting the default color instead of the real one, check out what context you are passing. It took me several hours to figure it out, I tried to spare some typing and simply used getApplicationContext() but it doesn't find the colors then...

    0 讨论(0)
提交回复
热议问题