我发现这个问题getString Outside of a Context or Activity的公认答案和讨论并不清楚。
我是Android新手,我正在尝试理解如何在模型类中引用我的资源字符串,以便能够正确地支持本地化。
具体地说,我的模型有一个Location属性,我希望能够为方位角的指南针序号返回一个字符串。因为像“北”这样的指南针序号需要本地化,所以我尝试将它们存储在我的strings.xml中。
我想我知道我需要应用程序上下文才能到达资源对象,但我想知道这是否可能在不传入上下文的情况下实现。在模型中存储UI上下文似乎违反了MVC。
为了实现这一点,我想在我的模型中包含一个这样的方法。第一个if显示了我如何尝试使用strings.xml条目。
public String compassOrdinalForBearing(float bearing) {
assert bearing >= 0.0 && bearing <= 360.0;
if ((bearing > 336.5) && (bearing <= 360.0))
//Problem here
return Context.getResources().getString(R.string.compass_ordinal_north);
else if ((bearing >= 0) && (bearing <= 22.5))
return "North";
else if ((bearing > 22.5) && (bearing <= 67.5))
return "Northeast";
else if ((bearing > 67.5) && (bearing <= 112.5))
return "East";
else if ((bearing > 112.5) && (bearing <= 157.5))
return "Southeast";
else if ((bearing > 157.5) && (bearing <= 202.5))
return "South";
else if ((bearing > 202.5) && (bearing <= 247.5))
return "Southwest";
else if ((bearing > 247.5) && (bearing <= 292.5))
return "West";
else if ((bearing > 292.5) && (bearing <= 337.5))
return "Northwest";
else
assert false;
return null;
}发布于 2011-10-06 04:47:07
通常所做的是对Application类进行子类化,保证只有一个实例。
应用程序子类:
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate(){
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}你的班级:
public String compassOrdinalForBearing(float bearing) {
Context context = MyApplication.getContext();
String north = context.getResources().getString(R.string.compass_ordinal_north);)
}但别忘了更改清单:
<application android:name="com.example.myapp.MyApplication">或者,您可以在实例化过程中只传入上下文,而不保留指向它的指针,因为几乎可以肯定这些对象将从上下文实例化。
private Static string NORTH = null;
public MyClass(Context context){
initializeDirections(context);
}
private static void initializeDirections(Context context){
if(NORTH == null){
NORTH = context.getResources().getString(R.string.compass_ordinal_north);
}
}最后,这两者的一种混乱组合,以防您确实不能在实例化时传入上下文,并且您不想将应用程序上下文保留在application子类中:
public class MyApplication extends Application {
@Override
public void onCreate(){
super.onCreate();
MyClass.initializeDirections(this);
}
}
public class MyClass{
private static String NORTH = null;
public static final void initializeDirections(Context context){
NORTH = context.getResources().getString(R.string.compass_ordinal_north);
}
}编辑:在一个不相关的注释中,至少从这个唯一的代码片段中,您可以删除所有的第一个条件句。如果它达到了那个特定的'else',那么第一个条件必然是真的。
例如:
else if ((bearing >= 0) && (bearing <= 22.5))
return "North";
else if ((bearing > 22.5) && (bearing <= 67.5))
return "Northeast";可能是:
else if (bearing <= 22.5)
return "North";
else if (bearing <= 67.5)
return "Northeast";如果bearing是!<= 22.5,它必然大于22.5。
这可能会提高您的可读性,也可能不会改善您的可读性,也可能不是您所希望的。只有一些可能不需要的两美分:)
发布于 2011-10-06 03:16:51
,但我想知道这是否有可能,而不需要传入上下文
不需要,您需要传入上下文。
我想您唯一需要本地化字符串资源的地方就是提供给用户的一些UI。UI始终是某些Activity (也是Context)的一部分,所以当您需要为模型获取本地化字符串时,拥有一个Context实例应该不是问题。
https://stackoverflow.com/questions/7666215
复制相似问题