我正在尝试从当前主题属性中为按钮提供颜色:android.R.attr.colorPrimaryR.attr.colorPrimary这应该返回黄色,但始终为我提供蓝色!我也在清单中设定了主题。
例如,使用android:background="?attr/colorPrimary"设置工具栏的backgroundcolor将提供正确的颜色,但如果它是从代码中设置的,则不会提供正确的颜色。
这就是我试图设置按钮颜色的方式:

    TypedValue typedValue = new TypedValue();
    App.getAppContex().getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
    buttonColor = typedValue.data;


    addButton.setText("SAVE");
    addButton.getBackground().setColorFilter(buttonColor, PorterDuff.Mode.MULTIPLY);

这是我的“黄色”主题
  <style name="AppTheme_Yellow" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primaryYellow</item>
    <item name="colorPrimaryDark">@color/primary_darkYellow</item>
    <item name="colorAccent">@color/accentYellow</item>
    <item name="android:textColorPrimary">@color/primary_textYellow</item>
    <item name="android:textColorSecondary">@color/secondary_textYellow</item>
    <item name="android:icon">@color/iconsYellow</item>
    <item name="actionOverflowButtonStyle">@style/OverFlowStyle</item>
    <item name="popupMenuStyle">@style/popupMenuStyle</item>

“黄色”主题背后的颜色:
<color name="primaryYellow">#FFC107</color>
<color name="primary_darkYellow">#FFA000</color>
<color name="primary_lightYellow">#FFECB3</color>
<color name="accentYellow">#607D8B</color>
<color name="primary_textYellow">#212121</color>
<color name="secondary_textYellow">#727272</color>
<color name="iconsYellow">#212121</color>
<color name="dividerYellow">#B6B6B6</color>

最佳答案

我在使用的全局应用程序上下文中发现了问题。
App.getAppContex().getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
因此,必须使用getActivity()或在其中完成ui wigdets的活动的上下文:

getActivity().getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);

关于android - android.R.attr.colorPrimary总是给我错误的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37498842/

10-12 00:33
查看更多