在Android中更改主题(Android Studio)

时间:2016-02-25 13:45:40

标签: java android xml android-studio background

我制作了4个按钮。每个按钮都能够使用something.changeToTheme(this,something.BLACK);将背景颜色更改为其他颜色。它工作正常,但在关闭应用程序并重新启动主题后始终设置为默认值。有没有办法保存上一个会话的背景并查看我重新打开应用程序时?

1 个答案:

答案 0 :(得分:1)

将您的switch更改为:

switch (cTheme)
{
    case BLACK:         
        int myTheme = R.style.Default
        activity.setTheme(myTheme);

        //Save your activity theme color
        saveTheme(myTheme);
    break;

    case YELLOW:
        int myTheme = R.style.Green
        activity.setTheme(myTheme);

        //Save your activity theme color
        saveTheme(myTheme);
    break;
}

并将您的onActivityCreateSetTheme(Activity activity)更改为:

public static void onActivityCreateSetTheme(Activity activity, Int cTheme)

保存方法

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

加载方法

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

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

    return theme;
}

重要提示:loadTheme()之前致电setContentView() ,以便onCreate()成为:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  int theme = loadTheme();        //Load your theme here!!!!
  CustomazationProcess.onActivityCreateSetTheme(this, theme);
  setContentView(R.layout.something1);

  findViewById(R.id.black).setOnClickListener(this);
  findViewById(R.id.yellow).setOnClickListener(this);
}

希望这能帮助你解决问题