簡體   English   中英

如何使用共享首選項保存和加載主題?

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

請幫幫我,已經 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>

和我的顏色。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>

最后是我的風格。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>

請幫幫我,我真的很想完成這項工作,我嘗試了幾個與我的問題相關的答案,例如: 在 Android (Android Studio) 中更改主題, 使用共享首選項保存 android 主題,使用共享首選項存儲 int 值如何將主題存儲在 Android 中的 SharedPreference 上如何更改 int 值 onclick 並將其傳遞給另一個活動? 在 android 上? 最后共享偏好不是持久的,但它們並沒有解決我的問題:(

在此鏈接: 更改 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);
    }

}

現在調試器 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)

很明顯,即使我稍微調整一下,它也不能正常工作,繼續前進。 接下來是: 使用共享首選項保存 android 主題

我用了最好的答案

現在的實用程序:

{
    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 我只想保留我選擇保留的主題,即使我退出應用程序並返回,如果這看起來有點復雜,我深表歉意

找到答案了!!! 首先,您需要確保在 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;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM