Sar*_*den 27 static android getstring
在为Android编程时,有时您必须使用静态方法.但是当您尝试以静态方法访问资源时,getString(R.string.text)您将收到错误.使其静止不起作用.
有没有人知道这个好方法?Android中的资源文件对于使用不同语言创建内容或更改文本非常有用.
小智 18
你可以用 Resources.getSystem().getStringArray(android.R.array.done);
这是我从静态方法内部访问资源的方法.也许不理想,但是.
首先,我扩展Application并设置一些公共静态字段,并创建一个初始化它们的方法:
public class MyApp extends Application {
// static resources
public static String APP_NAME;
public static void initResources(Context context) {
APP_NAME = context.getResources().getString(R.string.app_name);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的清单中,我注册了扩展的应用程序:
<application
android:name=".MyApp"/>
Run Code Online (Sandbox Code Playgroud)
在我的启动活动(MainActivity)中,我调用初始化静态资源:
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.initResources(this);
}
Run Code Online (Sandbox Code Playgroud)
然后在项目的任何地方,在运行MainActivity.onCreate(Bundle b)之后,您可以调用访问指定静态资源的静态方法:
public static void printAppName() {
Log.w("tag", "my app name: " + MyApp.APP_NAME);
}
Run Code Online (Sandbox Code Playgroud)
将Context(即Activity)实例作为参数对象传递给静态方法.然后调用getString参数.
| 归档时间: |
|
| 查看次数: |
29419 次 |
| 最近记录: |