英文:
How can I change Android theme in runtime without using recreate()?
问题
我在onCreate()中已经使用了setTheme(),如下所示:
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = Utility.GetTheme(this);
if(data.isDarktheme())
setTheme(R.style.DarkTheme);
else
setTheme(R.style.LightTheme);
setContentView(R.layout.activity_options);
...
所以,如果我在活动中使用recreate():
switch_theme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
setTheme(R.style.DarkTheme);
else
setTheme(R.style.LightTheme);
saveTheme();
recreate();
}
});
我的应用程序会冻结,我在另一个问题中读到它会陷入无限循环。有没有办法修复这个问题,最好是保持onCreate()开头的setTheme()代码?
英文:
I'm already using setTheme() in onCreate() like:
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = Utility.GetTheme(this);
if(data.isDarktheme())
setTheme(R.style.DarkTheme);
else
setTheme(R.style.LightTheme);
setContentView(R.layout.activity_options);
...
So if I use recreate() in the activity:
switch_theme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
setTheme(R.style.DarkTheme);
else
setTheme(R.style.LightTheme);
saveTheme();
recreate();
}
});
My app freezes as I read in another question that it goes into an infinite loop.
Is there any way to fix this, preferably with keeping that setTheme() in the beginning of onCreate()?
答案1
得分: 0
你可以使用 AppCompatDelegate.setDefaultNightMode(int)
来实现这一功能,你需要使用 DayNight
主题,并且在你的点击监听器中,你可以使用 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
或者 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
。
这里有一个链接可能对你有帮助:https://stackoverflow.com/questions/41724748/cannot-switch-between-modes-in-daynight-theme-dynamically
英文:
You could use AppCompatDelegate.setDefaultNightMode(int)
for that you need to use the DayNight
theme and on your clickListener you can do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
or AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
Here is a link that could help you: https://stackoverflow.com/questions/41724748/cannot-switch-between-modes-in-daynight-theme-dynamically
专注分享java语言的经验与见解,让所有开发者获益!
评论