在Android中更改主题(Android Studio) [英] Changing Theme in Android (Android Studio)

查看:57
本文介绍了在Android中更改主题(Android Studio)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made 4 buttons.Each button has the ability to change the background color to a different color using the something.changeToTheme(this, something.BLACK);.It works fine but after I close the app and restart it the theme is always set to default.Is there a way to save the background from the previous session and view that when I reopen the app?

推荐答案

将您的开关更改为:

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(活动活动)更改为:

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

重要提示::在之前 setContentView()调用 loadTheme(),这样您的 onCreate()应该类似于:

Important: call loadTheme() before setContentView() so your onCreate() should be like:

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

希望这可以帮助您

这篇关于在Android中更改主题(Android Studio)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆