【问题标题】:Restart current Activity to change application wide theme重新启动当前活动以更改应用程序范围的主题
【发布时间】:2014-05-01 14:05:22
【问题描述】:

根据我的研究,Android 没有实用的方法来更改整体应用程序主题。

我的应用程序有点简单,Activity 明智,我认为这种处理主题更改的方法是安全的。

我想知道下面的方法是否安全,或者这是一个黑客工作并且有更好的方法来实现应用程序范围的主题?

注意事项:

MainActivtiy.java是入口点,除了SettingsActivty.java之外的唯一Activity

SettingsActivity.java 扩展了PreferenceActivty 以显示典型的首选项屏幕。主题设置存储在R.string.colorThemeListPrefStr 标识的默认共享首选项中,其中android:entryValues 是{"0", "1"}

Settings.java 只是一个静态变量类,当应用程序在内存中时它是安全的,任何需要在会话之间保存的东西都会在onPause() 期间保存到共享首选项中。

MainActivity.java:

public class MainActivity extends ListActivity implements OnClickListener{

    public void onCreate(Bundle savedInstanceState) {
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        // get the int representing the theme selected from shared preferences
        switch (Integer.valueOf(sp.getString(getString(R.string.colorThemeListPrefStr), Settings.DEFAULT_COLOR_THEME_INDEX))) {
        case 0:
            super.setTheme(android.R.style.Theme_Light);
            break;
        case 1:
            super.setTheme(android.R.style.Theme_Black);
            break;
        }
        super.onCreate(savedInstanceState);
        // ...
    }

    public void onPause() {
        super.onPause();
        // ...
        // store the current theme int
        Settings.currentTheme = Integer.valueOf(sp.getString(getString(R.string.colorThemeListPrefStr), Settings.DEFAULT_COLOR_THEME_INDEX));
        // ...
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.inputSettingsButton:
            startActivityForResult(new Intent(this, SettingsActivity.class), Settings.PREFERENCES_REQUEST_CODE);
            break;
        // ...
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case Settings.PREFERENCES_REQUEST_CODE:
            // check if the new and old themes are different
            if (Settings.currentTheme != Integer.valueOf(sp.getString(getString(R.string.colorThemeListPrefStr), Settings.DEFAULT_COLOR_THEME_INDEX))) {
                this.finish();
                startActivity(new Intent(this, MainActivity.class));
            }
            break;
            // ...
        }
    }
}

【问题讨论】:

    标签: android android-activity android-theme


    【解决方案1】:

    您应该使用support library 附带的这一简单的一行代码重新启动您的Application

    startActivity(IntentCompat.makeRestartActivityTask(getActivity().getComponentName()));
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多