Neelay Srivastava Neelay Srivastava - 3 months ago 13
Android Question

How to change the color primary,color primarydark ,etc

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?



Answer

First step: make one theme per color-option:

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