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.
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:
All offering the same solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With