Automatically recreate activities on theme change

This commit is contained in:
Thialfihar
2015-06-25 19:22:13 +02:00
parent e51eff4050
commit 4d412d53dc
2 changed files with 62 additions and 4 deletions

View File

@@ -33,6 +33,7 @@ import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
@@ -59,10 +60,13 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
private PreferenceScreen mKeyServerPreference = null;
private static Preferences sPreferences;
private String mCurrentTheme = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
sPreferences = Preferences.getPreferences(this);
changeTheme();
super.onCreate(savedInstanceState);
setupToolbar();
@@ -114,6 +118,35 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
}
@Override
protected void onResume() {
super.onResume();
if (changeTheme()) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
protected boolean changeTheme() {
String newTheme = sPreferences.getTheme();
if (mCurrentTheme != null && mCurrentTheme.equals(newTheme)) {
return false;
}
int themeId = R.style.LightTheme;
if ("dark".equals(newTheme)) {
themeId = R.style.DarkTheme;
}
ContextThemeWrapper w = new ContextThemeWrapper(this, themeId);
getTheme().setTo(w.getTheme());
mCurrentTheme = newTheme;
return true;
}
/**
* Hack to get Toolbar in PreferenceActivity. See http://stackoverflow.com/a/26614696
*/

View File

@@ -18,6 +18,7 @@
package org.sufficientlysecure.keychain.ui.base;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
@@ -39,21 +40,45 @@ public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar mToolbar;
protected View mStatusBar;
private static Preferences sPreferences;
private String mCurrentTheme = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
sPreferences = Preferences.getPreferences(this);
changeTheme();
super.onCreate(savedInstanceState);
initLayout();
initToolbar();
}
@Override
protected void onResume() {
super.onResume();
if (changeTheme()) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
protected boolean changeTheme() {
String newTheme = sPreferences.getTheme();
if (mCurrentTheme != null && mCurrentTheme.equals(newTheme)) {
return false;
}
int themeId = R.style.LightTheme;
if ("dark".equals(sPreferences.getTheme())) {
if ("dark".equals(newTheme)) {
themeId = R.style.DarkTheme;
}
ContextThemeWrapper w = new ContextThemeWrapper(this, themeId);
getTheme().setTo(w.getTheme());
mCurrentTheme = newTheme;
super.onCreate(savedInstanceState);
initLayout();
initToolbar();
return true;
}
protected void initLayout() {