2014-12-02 64 views
-1

在我問之前,我已經看過this post,並嘗試了所有建議都無濟於事。我的問題是,我可以輕鬆設置使用如何從使用Android SDK的Java的string.xml中獲取字符串?

getResources().getString(R.string.example) 

的onCreate方法中的字符串,但我想設置使用相同的getResources()方法的公共靜態最終的String string.xml值。但是,當我這樣做時,我得到一個「無法從類型ContextThemeWrapper」的非靜態方法getResources()的靜態引用「。所以,我想實例ContextThemeWrapper也

this.getResources().getString(R.string.example) 

這既清除錯誤,但兩者的碰撞與一個NullPointerException。任何簡單地從資源設置一個字符串的解決方案將不勝感激。

到目前爲止,我有這樣的:

public class MainActivity extends Activity { 

    ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(); 
    public final String CYPHER = contextThemeWrapper.getResources().getString(R.string.cypher_txt); 
    public static final int LAYERS = 7; 
    public static final int FLIP = 3; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     String appName = getResources().getString(R.string.app_name); 
     Toast.makeText(this, "Welcome to " + appName, Toast.LENGTH_SHORT).show(); 

    } 

回答

1

你需要的是一個靜態的上下文對象。爲此,您可以使用應用程序上下文。

假設你的應用程序清單如下:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="my.app.package" ... 

     <application android:name=".MyApp" ... 

1)與公共靜態方法返回此背景下創建一個應用程序類。

package my.app.package; // This should match the package path in your Manifest 

public class MyApp extends android.app.Application { // This should match the app name in your manifest 

    private static MyApp appContext; 

    public MyApp() { appContext = this; } 

    public static Context getAppContext() { return appContext; } 

} 

2)然後在你的活動,可以使靜態獲取的背景和解決資源:

public final String CYPHER = MyApp.getContext().getResources.getString(R.string.cypher_txt); 
+0

@TheFreddyKilo - 這是否對你的工作? – EJK 2014-12-02 03:08:49

+0

應該是'MyApp extends Application',唯一不起作用的是在字符串有多個語言版本時切換設備區域設置,因爲它只加載一次,但從不更新。 – zapl 2014-12-02 03:31:12

+0

那麼這種方法是否解決了您原先提出的問題?處理多種語言是一個不同的問題,這不是你的問題。 – EJK 2014-12-02 04:03:31

相關問題