【问题标题】:how do i save and load theme using shared preferences?如何使用共享首选项保存和加载主题?
【发布时间】:2020-07-10 12:11:09
【问题描述】:

请帮帮我,已经 3 天了,我仍然不明白为什么我的共享偏好没有保存或加载我的主题

这是我的主要活动


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;
    }

}

这是我的工具

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;
        }
    }
}

这是我的 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>

还有我的 color.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>

最后是我的 style.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>

请帮帮我,我真的很想完成这项工作,我已经尝试了几个与我的问题相关的答案,例如:Changing Theme in Android (Android Studio)save android theme using shared preferencesStoring an int value using Shared preferencesHow to store theme on SharedPreference in AndroidHow to change the int value onclick and pass it to another activity ? on android?,最后是@ 987654326@ 但是 他们没有解决我的问题:(

在这个链接:Changing Theme in Android (Android Studio)

我尝试将答案应用到我的应用中

现在 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;
        }
    }
}

和主要活动

{
    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);
    }

}

现在是调试器输出

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)

很明显,即使我稍微调整一下,它也不能正常工作,继续前进。 接下来是这个:save android theme using shared preferences

我用了最好的答案

现在是 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;
        }
    }
}

和主要活动:

{
    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();
    }


}

还有我的 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
}

现在,当我退出应用程序时,它会返回默认主题,并且不会存储 int 我只想保留我选择保留的主题,即使我退出应用程序并返回,如果这看起来有点复杂,我深表歉意

【问题讨论】:

  • 不要说“我已经尝试了几个相关的答案...”,这无助于我们理解您的尝试,请告诉和显示您尝试过的细节,甚至可能包括这些问题的链接,并告诉/显示您在这些尝试中遇到了什么问题。
  • 您已经发布了链接,但尚未发布您尝试过的什么,您的尝试如何不起作用,...正如@HovercraftFullOfEels 评论中所要求的那样。跨度>
  • 完成,先生,它可能看起来有点复杂
  • 嘿伙计们,我自己解决了问题,发现问题并解决了,感谢您的帮助

标签: java android themes sharedpreferences


【解决方案1】:

找到答案!!!首先,您需要确保在 UTILS 上这样做

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

应该是这样的

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

它应该总是匹配“开关”部分

关于你的活动/主要活动的第二件事

而不是使用“保存主题”, 像这样将您的主题直接保存在 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;
        }

    }

最后像这样使用“加载主题”

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

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

        return theme;
    }

总而言之,这是我的主要活动

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;
    }

}

还有我的 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多