2014-12-02 2 views
-1

내가 물어보기 전에, 나는 이미 this post을보고 아무 제안도 시도하지 않았다. 내 문제는 내가 쉽게에서 onCreate 메소드 내Android SDK를 사용하여 Java의 string.xml에서 문자열을 가져 오는 방법은 무엇입니까?

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

를 사용하여 문자열을 설정할 수 있다는 것입니다,하지만 난 같은의 GetResources() 메소드를 사용하여 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

+0

은'MyApp extends Application'이어야합니다. 단 한 번로드되었지만 결코 업데이트되지 않기 때문에 여러 언어 버전의 문자열이있을 때 장치 로케일을 전환하는 것이 유일한 방법입니다. – zapl

+0

이 접근법은 처음에 언급 한 질문을 수정합니까? 여러 언어를 다루는 것은 당신의 질문에 다른 관심사입니다. – EJK

관련 문제