java - 使用复选框更改应用程序主题(使用java)

标签 java android checkbox toolbar android-toolbar

我正在向我的应用添加深色模式,并在三点菜单(工具栏)中创建了一个复选框。

我想让应用程序在选中该复选框时将主题更改为“深色”,并在取消选中时将其恢复为主主题。

这是我当前的深色模式复选框按钮 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( 之前使用 setTheme(...) ) (代码来自 this question ):

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/

相关文章:

html - CSS Transition 和复选框标签的问题

jsf-2 - 使用 PrimeFaces 下拉列表中的复选框进行多项选择

java - 通过取消选中复选框错误默认禁用编辑文本

android - Phonegap 安卓权限

iphone - 今天从网络应用程序访问智能手机传感器/地址簿?

java - 如何进行加密和解密?

Java Unicode 到 TextArea

android - 安卓版 clamav

java - 如何使用RelativeLayout ViewGroup 的OnClickListener?

java - 在Java中将ASCII字符串解析和处理为二进制是否有优势?