【问题标题】:Changing Theme in Android (Android Studio)在 Android (Android Studio) 中更改主题
【发布时间】:2016-06-08 07:58:15
【问题描述】:

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

【问题讨论】:

标签: java android xml android-studio background


【解决方案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);
}

希望对你有帮助

【讨论】:

  • 我刚刚用代码更新了我的问题,你认为它适用于我的吗?你能帮我在我的实现它吗?
  • 你想改变什么?按钮背景颜色?还是您的活动背景颜色?
  • 好的,我看看我能做什么
  • 这应该可以,但我目前无法访问android studio,所以我无法自己测试。
  • 应该可以,看this
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
相关资源
最近更新 更多