【问题标题】:How to reference an Android theme in preferences?如何在首选项中引用 Android 主题?
【发布时间】:2012-07-21 11:09:36
【问题描述】:

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

样式资源 ID 的获取和保存非常简单,但也可能在更新中发生变化。

样式名称似乎是更好的选择。如果是这样的话,如何根据资源 ID 获取主题名称,以及如何根据主题名称获取资源 ID?

【问题讨论】:

  • 您可以尝试使用 xml 解析器解析 xml 并检索值

标签: android android-theme android-resources android-styles


【解决方案1】:

我设法通过使用主题名称和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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多