user5366495
user5366495

Reputation:

android.R.attr.colorPrimary gives me the wrong colors all the time

I'm trying to give my buttons colors from the current themes attributes: android.R.attr.colorPrimary or R.attr.colorPrimary which should return Yellow, but gives me a blue color all the time instead! I have also set the theme in the manifest.

Setting for example the backgroundcolor of the toolbar with android:background="?attr/colorPrimary" gives the correct color, but not if it set from the code.

This is how I'm trying to set the color of my button:

    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);

This is my "Yellow" theme

  <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>

The colors behind the "Yellow" theme:

<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>

Upvotes: 2

Views: 2112

Answers (1)

user5366495
user5366495

Reputation:

I found the problem in the global Application context I was using. App.getAppContex().getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);

So one must use the the getActivity() or the Context of the activity where the UI Wigdets is inilitized in:

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

Upvotes: 5

Related Questions