android - 根据当前设置的主题获取属性颜色值

标签 android android-theme

在我的 Activity 中,我正在维护一个 SuperActivity,我在其中设置主题。

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

主题.xml

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

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

如本可能 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 上下文?

最佳答案

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

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() 但它没有找到颜色......

关于android - 根据当前设置的主题获取属性颜色值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23320577/

相关文章:

Android 微调器在按钮本身上没有波纹,只有它的选项

android - getColorStateList 已被弃用

android - 对话框主题动画问题

android - 如何完成当前 Android 任务中的所有 Activity ?

android - 如何在 Delphi 中使用自定义 debug.keystore?

android - 有没有办法在 Nativescript Android 应用程序中创建一个平面按钮?

android - 错误 : failed to find target with hash string 'android-21'

android改变背景颜色太慢

android - 是否可以从 styles.xml 文件中引用属性?

java - 更大尺寸屏幕中的布局间距问题