我目前正在執行我的應用程序的數據層,只是想知道what's的最佳方式從相應的android資源,如字符串,顏色等Android:如何從資源中分離純數據?
例如單獨的純數據類/信息:
public final class Location {
public static final int NOT_SPECIFIED = 0;
public static final int AT_HOME = 1;
public static final int AT_WORK = 2;
public static final int AWAY = 3;
public static final int[] VALUES = {
NOT_SPECIFIED, AT_HOME, AT_WORK, AWAY
};
@IntDef({ NOT_SPECIFIED, AT_HOME, AT_WORK, AWAY })
@Retention(RetentionPolicy.SOURCE)
public @interface Locations {}
private static String TXT_NOT_SPECIFIED;
private static String TXT_AT_HOME;
private static String TXT_AT_WORK;
private static String TXT_AWAY;
private Location() {}
/**
* Call once in Application.class to get a reference to the application context
* in order to load the string representations for the single locations.
*
* @param applicationContext the app´s context
*/
public static void init(Context applicationContext) {
Resources res = applicationContext.getApplicationContext().getResources();
/* Pre-load any string resources that correspond to locations. */
TXT_NOT_SPECIFIED = res.getString(R.string.text_location_not_specified);
TXT_AT_HOME = res.getString(R.string.text_location_at_home);
TXT_AT_WORK = res.getString(R.string.text_location_at_work);
TXT_AWAY = res.getString(R.string.text_location_away);
}
/**
* Returns the string representation of a given <code>location</code>.
*
* @param location must be in range of 0-3
*uhr
* @return the string representing the <code>location</code>
*/
public static String getStringForLocation(@Locations int location) {
switch (location) {
case NOT_SPECIFIED: return TXT_NOT_SPECIFIED;
case AT_HOME: return TXT_AT_HOME;
case AT_WORK: return TXT_AT_WORK;
case AWAY: return TXT_AWAY;
}
throw new IllegalStateException("'location' must be in range of 0-3"); /* Should never be called actually. */
}
該類本身包含某些位置的純數據表示(而不是使用enum
)。對於每個定義的location
,存在strings.xml
文件中存儲的字符串表示。 # 現在的問題是:我的應用程序的多個部分需要獲取某個location
的名稱。而不是每次我希望將它們存儲在一個地方時找到資源,以便如果有所更改(添加了新的location
選項等),我只需在一個地方觸摸代碼即可。
目前我已經實現了它,就像上面的代碼所示:Location
類有一個靜態init方法,它在應用程序的onCreate中被調用以獲得context
以加載字符串resoruces。 (我知道我可以剛剛通過context
作爲getStringForLocation
方法的參數,無法決定哪一個更好?)
但是,這種方式我在我所謂的純數據類中有android依賴關係。 什麼是分離這種依賴關係的好方法,同時仍然維護將數據映射到一個資源的代碼?在執行映射的數據層之外有靜態實用方法?
爲什麼*不*使用' enum'? – EJP
據我瞭解,這是不是在Android的首選方法,因爲內存或性能的原因。 Android程序員建議在註釋IntDef中使用整型常量。至少我是這麼理解的。 [https://www.youtube.com/watch?v=Hzs6OBcvNQE] – Elias