【问题标题】:Get attr color value based on current set theme根据当前设置的主题获取 attr 颜色值
【发布时间】:2014-06-12 18:55:51
【问题描述】:

在我的活动中,我维护了一个SuperActivity,我在其中设置了主题。

public class SuperActivity extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MyTheme);
    }
}

themes.xml

<!-- ImageBackround -->
<style name="Theme.MyTheme" parent="ThemeLight">
    <item name="myBgColor">@color/translucent_black</item>
</style>

现在我想在我的一个子活动中获取这种颜色。

正如这个可能的answer 中提到的,我写道:

int[] attrs = new int[] { R.attr.myBgColor /* index 0 */};
TypedArray ta = ChildActivity.this.obtainStyledAttributes(attrs);
int color = ta.getColor(0, android.R.color.background_light);
String c = getString(color);
ta.recycle();

但是每次我得到的默认值是android.R.color.background_light 而不是R.attr.myBgColor

我做错了。我是否传递了 ChildActivity.this 的错误上下文?

【问题讨论】:

    标签: android android-theme


    【解决方案1】:

    您有两种可能的解决方案(一种是您实际拥有的,但为了完整起见,我将两者都包括在内):

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

    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 当然可以是任何其他默认值。是的,正如您所怀疑的,上下文非常很重要。如果您一直获得默认颜色而不是真实颜色,请检查您传递的上下文。我花了几个小时才弄明白,我试着节省一些打字时间并简单地使用了getApplicationContext(),但它没有找到颜色......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多