简体   繁体   English

如何从 Strings.xml 文件中调用 mainactivity.xml 中的字符串

[英]how to call Strings in mainactivity.xml from Strings.xml file

  1. I want to Call it in TextView我想在 TextView 中调用它

    <string name="Std_Name">Name: Muhammad Abdullah</string> <string name="Std_Phone">Phone: +923338157028</string>

If you want to add the value from strings.xml to TextView in mainactivity.xml , add the following line of code to your xml如果要将 strings.xml 中的值添加到mainactivity.xml中的TextView ,请将以下代码行添加到您的 xml

android:text="@string/Std_Name"

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="5sp"
    android:lineSpacingExtra="2sp"
    android:text="@string/Std_Name" // Add this line to your textView
    android:textColor="@color/yellow_dark"
    android:textSize="@dimen/activity_text_size_small"
    android:textStyle="normal" />

Or, if you want to add text from strings.xml to textview from MainActivity.java , add the following code或者,如果您想将strings.xml中的文本添加到MainActivity.java中的 textview,请添加以下代码

TextView textView = findViewById(R.id.textView1);
textView.setText(getResources().getString(R.string.Std_Name));

From within an XML layout, you can use the @string/resourceName syntax within the text string to reference a string resource:在 XML 布局中,您可以使用text字符串中的@string/resourceName语法来引用字符串资源:

android:text="@string/resourceName"

Using the Std_Name string resource from your example, that would look something like this:使用示例中的Std_Name字符串资源,看起来像这样:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/Std_Name" />

Official documentation for string resources can be found here .字符串资源的官方文档可以在这里找到。 You can also find a good example in the Accessing resources from XML section of the App resources overview .您还可以在应用程序资源概述从 XML 访问资源部分找到一个很好的示例。

Try this尝试这个

String myName = getResources().getString(R.string.Std_Name);
String myPhone = getResources().getString(R.string.Std_Phone);

// Then do whatever you want with these values

在您的 Textview 文本字段中调用

android:text="@string/Std_Name"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM