2011-05-02 42 views
3

我已經看過並嘗試了很多東西,但它似乎我的應用程序沒有獲取strings.xml中的字符串值。它實際上似乎是空白。我認爲有一個初始化問題。使用strings.xml w/Android

的strings.xml

<string name="itb_cityID">2</string> 
     <string name="itb_city">New York</string> 

constants.java摘錄:

public class ConstantData { 

public static String cityID="2"; 
public static String city="New York"; 

如何設置cityID = R.strings.itb_cityIDcity=itb_city正確的方法是什麼?

回答

13

String yourString = Context.getResources().getString(R.string.your_string);

注:不能使用Context靜態。如果您在活動內部,只需使用this或直接撥打getResources()即可。否則,您需要通過getApplicationContext()獲得應用程序上下文的句柄。

+0

確定,所以當我做到這一點,字符串\t = cityID Context.getResources()的getString(R.string.itb_cityID)。我得到一個「上下文無法解決」,並給出8個選項來修復 感謝您的快速回復! – basemansix8 2011-05-02 19:02:02

+2

嘗試使用getApplicationContext()來檢索上下文。 – ChrisJ 2011-05-02 19:04:06

+0

我的行看起來像使用getResources或getApplicationContext? – basemansix8 2011-05-02 19:26:49

0

您是否檢查過整個項目沒有錯誤?如果不存在,可能會導致R.java無法使用字符串進行更新。你可以嘗試從「項目」菜單中「清理」你的投影。這可能有效。此外,我不明白爲什麼你必須使用Context.,通常你應該能夠直接撥打getResources().(在某些情況下,即使這是不必要的)。要查找的好處是,如果在strings.xml文件中聲明的字符串被識別爲聲明的字符串。

7

這個例子可能是保存在RES /價值/ strings.xml中有用

  • XML文件:

    <?xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <string name="hello">Hello!</string> 
    </resources> 
    
  • 這種佈局XML應用的字符串到View

    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello" /> 
    
  • 此應用程序代碼檢索字符串:

    String string = getString(R.string.hello);

    您可以使用的getString(INT)或gettext的(INT)來檢索字符串。 getText(int)將保留應用於該字符串的任何富文本樣式。

這個例子是從http://developer.android.com/guide/topics/resources/string-resource.html