Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change theme in Android app [duplicate]

I want dynamically change the theme of my app with buttons, so I implemented this:

 sharedPreferences = getSharedPreferences("VALUES",MODE_PRIVATE);
    int theme = sharedPreferences.getInt("THEME",2);

    switch (theme){
        case 1: setTheme(R.style.AppTheme);
            break;
        case 2: setTheme(R.style.AppTheme_AppBarOverlay);
            break;
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tutotial);

And this is the code of the buttons:

        tb1 =(Button) findViewById(R.id.button2);

    tb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sharedPreferences.edit().putInt("THEME",1).apply();
            Intent intent = new Intent(tutotial.this, tutotial.class);
            startActivity(intent);
        }
    });

tb2 =(Button) findViewById(R.id.button3);

    tb2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sharedPreferences.edit().putInt("THEME",2).apply();
            Intent intent = new Intent(tutotial.this, tutotial.class);
            startActivity(intent);
            Intent intent1 = new Intent(tutotial.this, MainActivity.class);
            startActivity(intent1);

        }
    });

The problem is that code just changes the theme of the activity associated and it does not make the change theme in all the app.

like image 522
Fernando Luján Martínez Avatar asked Jun 15 '26 02:06

Fernando Luján Martínez


1 Answers

There is an open source podcast player called AntennaPod on github. It contains example code that does this.

The way they do it is to call ContextThemeWrapper.setTheme(int) at the beginning of each Activity.onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(UserPreferences.getTheme());
    super.onCreate(savedInstanceState);
    ......
}

This could be done in each activity, or by creating a base activity that does this for you on each subclass.


On closer reading of your question, this is exactly what you are doing. So I would say you are on the right track.


It also seems this has been asked before:

  • Switching application-wide theme programmatically?
  • Android - Change app Theme on onClick
  • I want my users to be able to switch from a dark and light theme for my entire app

All offering the same solution.

like image 165
2 revsRichard Le Mesurier Avatar answered Jun 18 '26 00:06

2 revsRichard Le Mesurier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!