我目前正在实现我的应用程序的数据层,并且想知道从相应的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方法,在App的onCreate中调用它来获取context
以加载字符串resoruces。 (我知道我可能刚刚将context
作为getStringForLocation
方法的参数传递,无法确定哪一个更好?)
然而,这种方式我在我假设的纯数据类中有android依赖。 在保持将数据映射到一个地方的资源的代码的同时,分离这些依赖关系的好方法是什么?在数据层外部使用静态util方法进行映射?
答案 0 :(得分:0)
我不太明白为什么要在某些变量中预加载字符串。我的理解是从资源中获取字符串在性能方面并不昂贵。
我只是使用这样的东西:
public static String getLocationString(Context context, @Locations int location) {
switch (location) {
case NOT_SPECIFIED: return context.getString(R.string.text_location_not_specified);
case AT_HOME: return context.getString(R.string.text_location_at_home);
case AT_WORK: return context.getString(R.string.text_location_at_work);
case AWAY: return context.getString(R.string.text_location_away);
}
throw new IllegalStateException("'location' must be in range of 0-3"); /* Should never be called actually. */
}
来自活动:
String myLocation = Location.getLocationString(this, Location.AT_HOME);
你可以摆脱Location.init
方法