0

如何在不为每个主题定义常量的情况下将主题保存在首选项中?

样式资源 ID 很容易获取和保存,但也可能在更新中更改。

样式名称似乎是更好的选择。如果这是这样做的方法,你如何获得给定资源 ID 的主题名称,以及如何获得给定主题名称的资源 ID?

4

1 回答 1

0

我设法通过使用主题名称和getResourceEntryName来解决这个问题。完整代码:

public static final String PREFERENCE_THEME = "theme";
public static final int[] THEMES = {R.style.Theme_Blue, R.style.Theme_Green, R.style.Theme_Orange, R.style.Theme_Purple, R.style.Theme_Red};
private static final int DEFAULT_THEME = R.style.Theme_Green;

public int getTheme() {
    final String themeName = preferences.getString(PREFERENCE_THEME, getThemeName(DEFAULT_THEME));
    for (int i = 0; i < THEMES.length; i++) {
        int resId = THEMES[i];
        String candidateThemeName = this.getThemeName(resId);
        if (themeName.equals(candidateThemeName)) {
            return resId;
        }
    }
    // The theme in preferences doesn't exist anymore
    this.setTheme(DEFAULT_THEME);
    return DEFAULT_THEME;
}

public void setTheme(int resId) {
    final String themeName = getThemeName(resId);
    Editor editor = preferences.edit();
    editor.putString(PREFERENCE_THEME, themeName);
    editor.commit();
}

private String getThemeName(int resId) {
    return context.getResources().getResourceEntryName(resId);
}
于 2012-07-21T12:32:51.737 回答