简体   繁体   English

将背景图像更改为android studio中的主题更改

[英]Change background image as theme changes in android studio

I want to change the theme of my app by a switch button. 我想通过切换按钮更改我的应用程序的主题。 There is no problem and the theme changes into dark or light as I hit the button. 当我按下按钮时,没有问题,主题变为黑暗或浅色。 on the other hand, I want to change the background image as the theme changes in different activities. 另一方面,我想改变背景图像,因为主题在不同的活动中发生变化。 I mean the MainActivity has an image background and other activities have their own background image. 我的意思是MainActivity有一个图像背景,其他活动有自己的背景图像。 I would be very grateful if there is a guy to help me. 如果有人帮助我,我将非常感激。

this is my code: 这是我的代码:

private Switch mySwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode() == 
AppCompatDelegate.MODE_NIGHT_YES){
        setTheme(R.style.darkTheme);
}
else {setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mySwitch = (Switch) findViewById(R.id.my_switch);
if(AppCompatDelegate.getDefaultNightMode() == 
AppCompatDelegate.MODE_NIGHT_YES){
mySwitch.setChecked(true);
}else {
}

mySwitch.setOnCheckedChangeListener(new 
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) 
{
if(b){AppCompatDelegate.setDefaultNightMode 
(AppCompatDelegate.MODE_NIGHT_YES);
restartApp();
}
else {

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
restartApp();
}
}
});
}

public void restartApp(){
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
}

Saving content in sharedPref 在sharedPref中保存内容

private SharedPreferences mSharedPreferences;

public SharedCache(SharedPreferences sharedPreferences) {
    mSharedPreferences = sharedPreferences;
}

public String getThemeName() {
    return mSharedPreferences.getString(THEME_NAME, APP_DARK);
}

public void setThemeName(@NonNull String theme) {
    mSharedPreferences.edit().putString(THEME_NAME, theme).apply();
}

Here AppDark is my current theme name , you can set your theme name onChange of your theme . 这里AppDark是我当前的主题名称,您可以在主题的更改上设置主题名称。

In Activity onCreate method , get the theme from sharedPref . 在Activity onCreate方法中,从sharedPref获取主题。 Or you can follow the below link for better understanding on sharedPreference . 或者,您可以按照以下链接更好地了解sharedPreference。 https://medium.com/android-grid/android-sharedpreferences-example-writing-and-reading-values-7a677f4448c3 https://medium.com/android-grid/android-sharedpreferences-example-writing-and-reading-values-7a677f4448c3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM