Java 如何访问random string.xml

Java 如何访问random string.xml,java,android,xml,string,findviewbyid,Java,Android,Xml,String,Findviewbyid,一个简单的引用生成器正在讨论中,我已经对代码进行了概念化,并假设如果我将字符串保存在xml中,它将工作 <resources> <string name="app_name">"Lift Quote"</string> <string name="action_settings">Settings</string> <!-- put buttons in here --> <!-- he

一个简单的引用生成器正在讨论中,我已经对代码进行了概念化,并假设如果我将字符串保存在xml中,它将工作

<resources>
    <string name="app_name">"Lift Quote"</string>
    <string name="action_settings">Settings</string>
    <!-- put buttons in here -->
    <!-- here are the quotes -->
    <!-- inspiring -->
    <string name="s1">"He who has a why to live can bear almost any how." -Nietzche</string>
    <string name="s2">"Life is about making an impact, not making an income." –Kevin Kruse</string>
    <string name="s3">You miss 100% of the shots you don’t take. –Wayne Gretzky</string>
    <!-- deep -->
    <string name="s4">" A man's character is his fate. " -Heraclitus</string>
    <string name="s5">"Why do you stay in prison when the door is so wide open?" -Rumi</string>
    <string name="s6">"When I let go of what I am, I become what I might be." -Lao Tzu</string>
    <!-- positive -->
    <string name="s8">"Happiness is not something ready made. It comes from your own actions." -Dalai Lama</string>
    <string name="s9">"If you have a positive attitude and constantly strive to give your best effort,
        eventually you will overcome your immediate problems and find you are ready for greater challenges." -Pat Riley
</string>

</resources>
我想我的问题更多:如何通过字符串变量访问String.xml值。我发现这在将来可能有用。
目前,我选择在一个单独的类中通过数组来实现这一点。

使用
getResources().getIdentifier(“s1”,“string”,Activity.this.getPackageName())
获取资源id。然后调用
txt.setText(id)
使用
getResources().getIdentifier(“s1”,“string”,Activity.this.getPackageName())
获取资源id。然后调用
txt.setText(id)

在strings.xml中的
字符串数组中定义引号,如下所示

<string-array name="mystrings">
        <item>value 1</item>
        <item>value 2</item>
        <item>value 3</item>
</string-array>

在strings.xml中的
字符串数组中定义引号,如下所示

<string-array name="mystrings">
        <item>value 1</item>
        <item>value 2</item>
        <item>value 3</item>
</string-array>
试试这个:

假设您需要以下字符串名称:

final String ss1 = "s1";
您可以获取具有该名称的字符串(动态地作为字符串),如下所示:

final String x = getString(getApplicationContext().getResources().getIdentifier(ss1, "string", getPackageName()));
试试这个:

假设您需要以下字符串名称:

final String ss1 = "s1";
您可以获取具有该名称的字符串(动态地作为字符串),如下所示:

final String x = getString(getApplicationContext().getResources().getIdentifier(ss1, "string", getPackageName()));

我觉得这样比较容易。然后从字符串数组中随机选取合适的字符串。我觉得这会更容易。然后从字符串数组中随机选取以获得适当的字符串。