Reputation: 1358
I need to set the application theme according to the user preference. This process happens in separate activity and it is not my main activity. I used this code to change the application theme:
getApplicationContext().setTheme(R.style.theme);
I know that it is perfectly work if I used it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
methods inside onCreate() method. But I have to do it in separate method. I tried to restart the application after that code as follows but it is not restart the application.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
startActivity(intent);
Also I don't have any idea after restarting the application that it would work. Any suggestion would be appreciated to solve the problem to change the application theme programmatically .
Upvotes: 1
Views: 1336
Reputation: 519
If I understood you correctly, can you try saving the user preference choice? After the user chooses a theme, you can save the choice in persistent memory (such as shared preferences) and after the select, restart the application. In the onCreate of the main activity, you can access the user choice and set the theme there before super.onCreate( ) by accessing the persistent memory.
Upvotes: 1
Reputation: 21183
Try the following, it restarts the application after one second:
private void restartSelf() {
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 1000, // one second
PendingIntent.getActivity(this, 0, getIntent(), PendingIntent.FLAG_ONE_SHOT
| PendingIntent.FLAG_CANCEL_CURRENT));
finish();
}
restartSelf()
should be a member of your main activity. Alternatively, you may replace this
with your application's context and and getIntent()
with the main activity's Intent
.
Upvotes: 2