如何在偏好中保存主题而不为每个主题定义常量?
样式资源ID非常容易获取和保存,但也可能在更新中发生变化。
样式名称似乎是更好的选择。如果这是这样做的,那么如何获得主题名称给定其资源ID,以及如何获得给定主题名称的资源ID?
答案 0 :(得分: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);
}