Java Android如何在所有活动中动态更改主题?

Java Android如何在所有活动中动态更改主题?,java,android,Java,Android,我试图在所有活动中动态切换背景主题。但目前,我只能让它打开开关所在的当前活动。 我尝试了以下方法: 使用setTheme为其他活动设置主题,但导致错误:找不到符号方法setTheme(int): 还尝试了getTheme,但导致错误:无法从静态上下文引用非静态方法getTheme() Resources.Theme theme = super.getTheme(); theme.applyStyle(R.style.darktheme,true); 请提供有关如何修复这些错误或其他方法的指导

我试图在所有活动中动态切换背景主题。但目前,我只能让它打开开关所在的当前活动。 我尝试了以下方法:

使用
setTheme
为其他活动设置主题,但导致错误:
找不到符号方法setTheme(int)

还尝试了
getTheme
,但导致错误:
无法从静态上下文引用非静态方法getTheme()

Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.darktheme,true);
请提供有关如何修复这些错误或其他方法的指导


更新,首选项管理器遇到新问题: 这是当前实现的,当切换时,黑暗主题应显示在各个活动中,但应用程序完全变黑,没有错误:

myswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (isChecked){

                PreferenceManager
                        .getDefaultSharedPreferences(DisplaySettingActivity.this)
                        .edit()
                        .putInt("ActivityTheme", R.style.darktheme)
                        .commit();
                DisplaySettingActivity.this.recreate();
            }

您可以尝试创建一个改变主题的baseActivity,然后对该活动进行子类化并修改主题。让我知道扩展Saham的答案是否有效,这可以通过子类化Activity和重写onCreate()来解决:

现在,将要更改主题的所有活动从MechangActivity扩展到extend。只要您想更改活动的主题,您就可以使用以下方法:

PreferenceManager
    .getDefaultSharedPreferences(this)
    .edit()
    .putInt("ActivityTheme", R.id.theme_you_want_to_set)
    .commit();

感谢您的帮助,您能否查看有关实现此方法时出现的问题的更新。Show R.style.darktheme使用此方法对我不起作用。accentColor、colorPrimary等没有改变。唯一改变的是状态栏/导航栏。我尝试使用android名称空间作为属性的前缀,但没有成功。感谢您的帮助,您能否查看有关实现此功能时出现的问题的更新。
public class ThemeChangeActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Gets the saved theme ID from SharedPrefs, 
        // or uses default_theme if no theme ID has been saved
        int theme = PreferenceManager.getDefaultSharedPreferences(this).getInt("ActivityTheme", R.id.default_theme);
        // Set this Activity's theme to the saved theme
        setTheme(theme);
        // Continue with creation
        super.onCreate(savedInstanceState);
    }
}
PreferenceManager
    .getDefaultSharedPreferences(this)
    .edit()
    .putInt("ActivityTheme", R.id.theme_you_want_to_set)
    .commit();