简体   繁体   English

如何使用共享首选项保存和加载主题?

[英]how do i save and load theme using shared preferences?

please help me out, its been 3 days and i still don't understand why my shared preferences does not save or load my theme请帮帮我,已经 3 天了,我仍然不明白为什么我的共享偏好没有保存或加载我的主题

here is my main activity这是我的主要活动


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String SHARED_PREF = "sharedPrefs";


    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int LT = loadTheme(0);
        int ST = saveTheme(0);
        Utils.onActivityCreateSetTheme(this, LT,ST);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                loadTheme(0);
                saveTheme(0);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                loadTheme(1);
                saveTheme(1);
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                loadTheme(2);
                saveTheme(2);
                break;
        }

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

    public int loadTheme(int defval) {
        if (defval == 1) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 1);
            Toast.makeText(this, "LOADTHEMEVAL= 1", Toast.LENGTH_SHORT).show();

        } else if (defval == 2) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 2);
            Toast.makeText(this, "LOADTHEMEVAL= 2", Toast.LENGTH_SHORT).show();

        } else if(defval == 0) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 0);
            Toast.makeText(this, "LOADTHEMEVAL= 0", Toast.LENGTH_SHORT).show();

        }

        return defval;
    }
    public int saveTheme(int defval) {
        if (defval == 2) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 2);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
        } else if (defval == 1) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 1);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();

        } else if (defval == 0) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 0);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
        }
        return defval;
    }

}

here is my utils这是我的实用程序

package com.perz.themeactivity;
import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int theme, int them)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}

here is my activity_main.xml这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Theme default"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.101"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cerv_Theme"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.878"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Giant Theme"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.366"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/textcolor"
        android:text="PRIMARYLETTER"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.112"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/gaugebackcolor"
        android:text="COLOR SECONDARY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.553"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/gaugebackcolor"
        android:text="COLOR TERTIARY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.899"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

and my color.xml和我的颜色。xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#E80A0A </color>

    <color name="colorPrimaryDark">#E80A0A </color>
    <color name="colorPrimaryletter">#E80A0A</color>
    <color name="colorSecondary">#000000</color>
    <color name="colorTertiary">#E80A0A</color>
    <color name="colorAccent">#000000</color>
    <color name="pure_black">#000000</color>
</resources>

and lastly my style.xml最后是我的风格。xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="backgroundColor">@color/pure_black</item>
        <item name="textcolor">@color/colorPrimaryletter</item>
        <item name="gaugebackcolor">@color/colorSecondary</item>
        <item name="scalecolor">@color/colorTertiary</item>
        <item name="colorback">@color/colorAccent</item>
    </style>

    <style name="Cerv_Theme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- Customize your theme here. -->

        <item name="colorPrimary">#000000</item>
        <item name="colorPrimaryDark">#EFECEC</item>
        <item name="colorAccent">#000000</item>
        <item name="backgroundColor">#000000</item>
        <item name="textcolor">#EFECEC</item>
        <item name="gaugebackcolor">#FFFFFF</item>
        <item name="scalecolor">#000000</item>
        <item name="colorback">#000000</item>
    </style>

    <style name="Giant_Theme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- Customize your theme here. -->

        <item name="colorPrimary">#0143C6</item>
        <item name="colorPrimaryDark">#FFFFFF</item>
        <item name="colorAccent">#0439A3</item>
        <item name="backgroundColor">#000000</item>
        <item name="textcolor">#EFECEC</item>
        <item name="gaugebackcolor">#0143C6</item>
        <item name="scalecolor">#000000</item>
        <item name="colorback">#0439A3</item>
    </style>

</resources>

please help me out i really want to make this work, i've tried several answers related to my problem such as: Changing Theme in Android (Android Studio) , save android theme using shared preferences , Storing an int value using Shared preferences , How to store theme on SharedPreference in Android , How to change the int value onclick and pass it to another activity?请帮帮我,我真的很想完成这项工作,我尝试了几个与我的问题相关的答案,例如: 在 Android (Android Studio) 中更改主题, 使用共享首选项保存 android 主题,使用共享首选项存储 int 值如何将主题存储在 Android 中的 SharedPreference 上如何更改 int 值 onclick 并将其传递给另一个活动? on android? 在 android 上? and lastly Shared preferences are not persistent but they didn't fix my problem:(最后共享偏好不是持久的,但它们并没有解决我的问题:(

at this link: Changing Theme in Android (Android Studio)在此链接: 更改 Android 中的主题(Android Studio)

I tried to apply the answer to my app我试图将答案应用于我的应用程序

now the UTILS looks like this现在 UTILS 看起来像这样

package com.perz.themeactivity;
import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                int myTheme = R.style.AppTheme;
                activity.setTheme(myTheme);

                MainActivity obj0 = new MainActivity();
                obj0.saveTheme(myTheme);
                break;
            case THEME_WHITE:
                int myTheme1 = R.style.Cerv_Theme;
                activity.setTheme(myTheme1);

                MainActivity obj1 = new MainActivity();
                obj1.saveTheme(myTheme1);
                break;
            case THEME_BLUE:
                int myTheme2 = R.style.Giant_Theme;
                activity.setTheme(myTheme2);

                MainActivity obj2 = new MainActivity();
                obj2.saveTheme(myTheme2);
                break;
        }
    }
}

and the MAIN ACTIVITY和主要活动

{
    private static final String SHARED_PREF = "sharedPrefs";
    private static final int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;

    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int theme = loadTheme();
        Utils.onActivityCreateSetTheme(this,theme );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);

                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);

                break;
        }

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

    public int loadTheme(){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        //Load theme color
        int theme = sharedPreferences.getInt("Theme",THEME_DEFAULT); //RED is default color, when nothing is saved yet

        return theme;
    }
    public void saveTheme(int theme)
    {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor prefEditor = sharedPreferences.edit();
        prefEditor.putInt("Theme",theme);
    }

}

now the debugger output现在调试器 output

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.perz.themeactivity, PID: 23544
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.perz.themeactivity/com.perz.themeactivity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
        at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:537)
        at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:526)
        at com.perz.themeactivity.MainActivity.saveTheme(MainActivity.java:66)
        at com.perz.themeactivity.Utils.onActivityCreateSetTheme(Utils.java:30)
        at com.perz.themeactivity.MainActivity.onCreate(MainActivity.java:23)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)

clearly it does not work properly even if i tweak it a little, moving on.很明显,即使我稍微调整一下,它也不能正常工作,继续前进。 next is this: save android theme using shared preferences接下来是: 使用共享首选项保存 android 主题

i used the best answer我用了最好的答案

now the UTILS:现在的实用程序:

{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int theme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}

and the MAIN ACTIVITY:和主要活动:

{
    private static final String SHARED_PREF = "sharedPrefs";
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;

    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Utils.onActivityCreateSetTheme(this, new SharedPreferencesManager(this).retrieveInt("theme", THEME_DEFAULT));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {

        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_DEFAULT);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_WHITE);
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_BLUE);
                break;
        }

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


}

and my SHAREDPREFERENCEMANAGER和我的 SHAREDPREFERENCEMANAGER


package com.perz.themeactivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class SharedPreferencesManager {
    /**
     * SharedPreferences to store the settings. This way, they'll be available next time the user starts the app
     */
    private SharedPreferences sPreferences;
    /**
     * Editor to make changes on sharedPreferences
     */
    private SharedPreferences.Editor sEditor;

    /**
     * The class itself
     */
    private Context context;

    public SharedPreferencesManager(Context context) {
        this.context = context;
        sPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    private SharedPreferences.Editor getEditor() {
        return sPreferences.edit();
    }

    /**
     * Store a boolean value in sharedPreferences
     *
     * @param tag   identifies the value
     * @param value the value itself
     */

    public void storeBoolean(String tag, boolean value) {
        sEditor = getEditor();
        sEditor.putBoolean(tag, value);
        sEditor.commit();
    }

    /**
     * Store a string in sharedPreferences
     *
     * @param tag identifies the value
     * @param str the string itself
     */

    public void storeString(String tag, String str) {
        sEditor = getEditor();
        sEditor.putString(tag, str);
        sEditor.commit();
    }

    /**
     * @param tag      identifies the value
     * @param defValue default value
     * @return the stored or default value
     */

    public boolean retrieveBoolean(String tag, boolean defValue) {
        return sPreferences.getBoolean(tag, defValue);

    }

    /**
     * @param tag    identifies the string
     * @param defStr default string
     * @return the stored or default string
     */

    public String retrieveString(String tag, String defStr) {
        return sPreferences.getString(tag, defStr);
    }

    /**
     * @param tag      identifies the value
     * @param defValue default value
     * @return the stored or default value
     */
    public int retrieveInt(String tag, int defValue) {
        return sPreferences.getInt(tag, defValue);
    }

    /**
     * @param tag      identifies the value
     * @param defValue the value itself
     */
    public void storeInt(String tag, int defValue) {
        sEditor = getEditor();
        sEditor.putInt(tag, defValue);
        sEditor.commit();
    }
//Incorrect Bracket Closing Removal
}

now when i exit the app it returns to the default theme and it does not store the int i just want to the theme that i choose to remain even if i exitted the app and return, i apologize if this looks like a bit complicated现在,当我退出应用程序时,它返回到默认主题并且它不存储 int 我只想保留我选择保留的主题,即使我退出应用程序并返回,如果这看起来有点复杂,我深表歉意

FOUND OUT THE ANSWER!!!找到答案了!!! first you need to make sure that this at UTILS首先,您需要确保在 UTILS

public static void onActivityCreateSetTheme(Activity activity, int theme)
    {
        switch (sTheme)
        

should look like this应该是这样的

public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)

it should always match the "switch" part它应该始终匹配“开关”部分

second thing on your activity/mainactivity关于您的活动/主要活动的第二件事

instead of using "SAVE THEME", saved your themes directly on the onclicklistener like this而不是使用“保存主题”,而是像这样将您的主题直接保存在 onclicklistener 上

@Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                defval = 0;
                Reptheme += Utils.THEME_DEFAULT;
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPreferences.edit();
                prefEditor.putInt("Theme", Utils.THEME_DEFAULT);
                prefEditor.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                defval = 1;
                Reptheme += Utils.THEME_WHITE;
                SharedPreferences sharedPreferences1 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor1 = sharedPreferences1.edit();
                prefEditor1.putInt("Theme", Utils.THEME_WHITE);
                prefEditor1.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                defval = 2;
                Reptheme += Utils.THEME_BLUE;
                SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor2 = sharedPreferences2.edit();
                prefEditor2.putInt("Theme", Utils.THEME_BLUE);
                prefEditor2.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
                break;
        }

    }

lastly use the "LOAD THEME" like this最后像这样使用“加载主题”

public int loadTheme(){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);

        
        int theme = sharedPreferences.getInt("Theme",1); 

        return theme;
    }

so to summarize, this is my main activity总而言之,这是我的主要活动

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String SHARED_PREF = "sharedPrefs";
    int defval = 1;
    int Reptheme ;
    public Button button11, button22, button33;
    TextView value;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Utils.onActivityCreateSetTheme(this, loadTheme());

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
        value = (TextView) findViewById(R.id.textView4);

        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
        defval = sharedPreferences.getInt("Theme", + defval);

        value.setText("null" + defval);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                defval = 0;
                Reptheme += Utils.THEME_DEFAULT;
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPreferences.edit();
                prefEditor.putInt("Theme", Utils.THEME_DEFAULT);
                prefEditor.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                defval = 1;
                Reptheme += Utils.THEME_WHITE;
                SharedPreferences sharedPreferences1 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor1 = sharedPreferences1.edit();
                prefEditor1.putInt("Theme", Utils.THEME_WHITE);
                prefEditor1.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                defval = 2;
                Reptheme += Utils.THEME_BLUE;
                SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor2 = sharedPreferences2.edit();
                prefEditor2.putInt("Theme", Utils.THEME_BLUE);
                prefEditor2.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
                break;
        }

    }
    public void restartApp() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
    }
    public int loadTheme(){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);

        //Load theme colorfdsfdssdfsdfsfsd
        int theme = sharedPreferences.getInt("Theme",1); //RED is default color, when nothing is saved yet

        return theme;
    }

}

and my UTILS.java和我的 UTILS.java

import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}

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

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