Access string.xml Resource File from Java Android Code

前端 未结 5 1375
误落风尘
误落风尘 2021-01-30 12:25

How do you access the values in the res/values/string.xml resource file from the Android Activity class?

相关标签:
5条回答
  • 2021-01-30 12:36

    If getString(R.string.app_name); isn't working for you, you can pass context like this:

    context.getString(R.string.app_name);
    
    0 讨论(0)
  • 2021-01-30 12:36

    If you have the context of Activity, go with:

    getString(R.string.app_name);
    

    If you don't have the context, try below, you can get the context from activity using Constructor.

    mContext.getString(R.string.app_name);
    
    0 讨论(0)
  • 2021-01-30 12:38

    Put this code in res/values/string.xml

    <string-array name="planet"> 
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
    

    This code to be placed in res/layout/main.xml and remove default widgets present in main.xml.

    <ListView android:id="@+id/planet"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:entries="@array/planet"/>
    </LinearLayout>
    
    0 讨论(0)
  • 2021-01-30 12:41

    Well you can get String using,

    getString(R.string.app_name);
    

    And, you can get string-array using

    String arr[] = getResources().getStringArray(R.array.planet);
    for (int i = 0; i < arr.length; i++) {
            Toast.makeText(getBaseContext(),arr[i], Toast.LENGTH_LONG).show();  
    }
    
    0 讨论(0)
  • 2021-01-30 12:51

    strings.xml:

    <string name="some_text">Some Text</string>
    

    Activity:

    getString(R.string.some_text);
    
    0 讨论(0)
提交回复
热议问题