0

I am trying to make app which gives option to change the color primary ,color primary dark of the app. So the user has the option to change the colors as per the choice . I want to give this option in the setting .So the user can choose between black , dark blue ,greyblue ,etc .I know how to set the theme of the app in xml but I want to change the color of the hole app. I want to change the theme of all the activity and dialog in the app .As one can not change the theme of the app as here it is mentioned. this is why I want to make a different color file if possible

  1. Will I have to make different color files as we have to do for different language?

  2. If yes, How I can use the different color files then?

Community
  • 1
  • 1
Neelay Srivastava
  • 1,041
  • 3
  • 15
  • 46

1 Answers1

10

First step: make one theme per color-option in your res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.MyAwesomeApp.Base" parent="Theme.AppCompat">
        <!-- Your common styles -->
    </style>

    <style name="Theme.MyAwesomeApp.Blue" parent="Theme.MyAwesomeApp.Base">
        <item name="colorPrimary">@color/material_indigo_500</item>
        <item name="colorPrimaryDark">@color/material_indigo_700</item>
        <item name="colorAccent">@color/material_light_blue_A200</item>
    </style>

    <style name="Theme.MyAwesomeApp.Red" parent="Theme.MyAwesomeApp.Base">
        <item name="colorPrimary">@color/material_red_500</item>
        <item name="colorPrimaryDark">@color/material_red_700</item>
        <item name="colorAccent">@color/material_red_A200</item>
    </style>

</resources>

Second step: Override the onCreate() method of your activity in order to call setTheme() with the choosen theme:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(getThemeIdChoosenByUser())
    setContentView(R.layout.myAwesomeLayout)
}

If you have more than one activity make a base class and set the them like this

public abstract class ThemeAwareBaseActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(getThemeIdChoosenByUser());
    }

    private int getThemeIdChoosenByUser() {
        // Lookup in SharedPreferences etc.
    }
}

public class Activity1 extends ThemeAwareBaseActivity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.layout_for_activity1)
        // do extra stuff on your resources, using findViewById on your layout_for_activity1
    }
}
jediz
  • 4,459
  • 5
  • 36
  • 41
larsgrefer
  • 2,735
  • 19
  • 36