Android-获取R.string类型为int问题

254 阅读1分钟

在Android开发里,java代码中的常量一般定义在string.xml这个文件中,这样便于修改并且方便做国际化。这个string.xml的值会被R文件映射,所以可以看到R文件全是定义为int类型,就像是一个地址指引一样。

在不同的地方获取string.xml中的值,方法各不相同:

1.在 AndroidManifest.xml 与 layout等xml文件中:
    android:text="@string/resource_name"
2.在 Activity 中:
    方法一:  this.getString(R.string.resource_name);  
    方法二:  getResources().getString(R.string.resource_name);
3.在其他 java 文件(必须有ContextApplication
    context.getString(R.string.resource_name);
    application.getString(R.string.resource_name);