Android 如何从我的应用程序主题中获取原色?

Android 如何从我的应用程序主题中获取原色?,android,android-xml,android-theme,android-styles,android-color,Android,Android Xml,Android Theme,Android Styles,Android Color,在我的Android java代码中,如何引用主题中设置的颜色“colorPrimary” 我有以下主题定义: <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <item name="colorPrimary">@color/myColor1</item> <item name="colorPrimaryDark">@c

在我的Android java代码中,如何引用主题中设置的颜色“colorPrimary”

我有以下主题定义:

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">

    <item name="colorPrimary">@color/myColor1</item>
    <item name="colorPrimaryDark">@color/myColor2</item>      
    <item name="colorControlNormal">@color/myColor3</item>
    <item name="colorControlActivated">@color/myColor4</item>

</style>

@颜色/颜色1
@颜色/颜色2
@颜色/颜色3
@颜色/颜色4
我可以直接引用颜色资源(R.color.myColor1),但我更喜欢引用主题的primaryColor设置,以便在将来更改colorPrimary时保持一致

这可能吗?

使用以下方法:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int color = typedValue.data;

这似乎得到了一个不同的颜色,看起来像一个通用的安卓蓝色。可能是getTheme()获取的是默认主题,而不是实际为应用程序定义的主题吗?哦,对不起。如果您在onCreate之外使用此剪切,则需要使用mActivity.getTheme()。(onrate:mActivity=this)它应该可以工作。我在片段中使用了很多次,这是在其他片段和零问题中使用的。如果可以,请直接与gettheme联系,如果不可以,请拨打MainActivity.gettheme。。。或者getactivity.getTheme…@Mayec/对于现在面临此问题的任何人,请尝试使用对我有效的
typedValue.resourceId
。对于获得不同颜色的任何人,请检查R类是否是应用程序的resources类,而不是android.R类