我正在向我的应用添加深色模式,并在三点菜单(工具栏)中创建了一个复选框。
我想让应用程序在选中该复选框时将主题更改为“深色”,并在取消选中时将其恢复为主主题。
这是我当前的深色模式复选框按钮 onClick 代码:
if (id == R.id.dark_mode) {
switch (item.getItemId()) {
case R.id.dark_mode:
if (item.isChecked()) {
// If item already checked then unchecked it
item.setChecked(false);
} else {
// If item is unchecked then checked it
item.setChecked(true);
}
default:
return super.onOptionsItemSelected(item);
}
}
我如何使用java来做到这一点?
此外,我想让应用程序记住用户最后是否选择了深色模式。 (这实际上是必需的,因为重新启动 Activity 后,应用程序将返回到旧状态。)
最佳答案
要以编程方式更改应用的主题,您可以在 onCreate()
方法中的 super.onCreate( 之前使用
(代码来自 this question ):setTheme(...)
)
public void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme); // THIS IS WHERE THE THEME IS SET -- must go before super.onCreate()
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
但是,一旦应用程序已经运行,这不会改变主题。为此,您需要重新启动应用程序或仅更改 Activity 的背景而不实际更改主题。
重新启动应用程序:
代码来自this question ,马克回答:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
更改背景:
如果您需要在应用程序仍在运行时更改背景,您可以像这样设置布局的背景颜色(此处将其设置为红色):
layout.setBackgroundColor(Color.RED);
应用程序关闭后保存用户的选择:
执行此操作的最佳方法是使用 SharedPreferences
API。例如,如果您想将背景选择保存为字符串到 boolean 值键值对(其中键为字符串"background_is_dark"
,值为true
或 false
)你可以这样写:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("background_is_dark"), true); // here is where you would enter true or false
editor.commit();
要稍后访问该 boolean 值(例如在 onCreate()
中,当您需要决定设置哪个背景时),您将使用以下代码:
Context context = getActivity();
SharedPreferences isDark = context.getSharedPreferences(
"background_is_dark", Context.MODE_PRIVATE);
参见Android's documentation有关 SharedPreferences
API 的更多信息。
关于java - 使用复选框更改应用程序主题(使用java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48552975/