我写了这句话:
String Mess = R.string.mess_1 ;
获取字符串值,但不是返回字符串,而是返回integer类型的id。如何获取它的字符串值?我提到了string.xml文件中的字符串值。
我写了这句话:
String Mess = R.string.mess_1 ;
获取字符串值,但不是返回字符串,而是返回integer类型的id。如何获取它的字符串值?我提到了string.xml文件中的字符串值。
当前回答
你可以直接读取strings.xml中定义的值:
<resources>
<string name="hello">Hello StackOverflow!</string>
</resources>
并设置为一个变量:
String mymessage = getString(R.string.hello);
但是我们可以在视图中定义字符串:
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"/>
其他回答
**
我希望这个代码是有益的
**
String user = getResources().getString(R.string.muser);
例如,如果您想将字符串值添加到按钮,简单使用
android:text="@string/NameOfTheString"
在strings.xml中定义的文本是这样的:
<string name="NameOfTheString">Test string</string>
在Android中使用getResources()之前必须引用Context名称。
String user=getApplicationContext().getResources().getString(R.string.muser);
OR
Context mcontext=getApplicationContext();
String user=mcontext.getResources().getString(R.string.muser);
细节
Android Studio 3.1.4 Kotlin版本:1.2.60
Task
单线使用 最小的代码 使用编译器的建议
步骤1。应用程序()
获得应用程序上下文的链接
class MY_APPLICATION_NAME: Application() {
companion object {
private lateinit var instance: MY_APPLICATION_NAME
fun getAppContext(): Context = instance.applicationContext
}
override fun onCreate() {
instance = this
super.onCreate()
}
}
步骤2。添加int扩展名
inline fun Int.toLocalizedString(): String = MY_APPLICATION_NAME.getAppContext().resources.getString(this)
使用
strings.xml
<resources>
<!-- ....... -->
<string name="no_internet_connection">No internet connection</string>
<!-- ....... -->
</resources>
获取字符串值:
val errorMessage = R.string.no_internet_connection.toLocalizedString()
结果
解决方案1
Context context;
String mess = context.getString(R.string.mess_1)
解决方案2
String mess = getString(R.string.mess_1)