티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How can I get a resource content from a static context?

스태틱 컨텍스트에서 리소스 컨텐츠를 가져오는 방법은 무엇인가요?

 문제 내용 

I want to read strings from an xml file before I do much of anything else like setText on widgets, so how can I do that without an activity object to call getResources() on?

저는 `setText`와 같은 작업을 하기 전에 XML 파일에서 문자열을 읽고 싶습니다. 그렇다면 `getResources()`를 호출할 수 있는 Activity 객체가 없는 경우에는 어떻게 할 수 있을까요?

 

 

 

 높은 점수를 받은 Solution 

  1. Create a subclass of Application, for instance public class App extends Application {
  2. Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
  3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named mContext and create a static method that returns this field, e.g. getContext():
1. Application의 하위 클래스를 생성합니다. 예를 들어 `public class App extends Application`을 작성합니다.
2. AndroidManifest.xml에서 태그의 android:name 속성을 새 클래스에 맞게 수정합니다. 예를 들어 `android:name=".App"`으로 수정합니다.
3. 앱 인스턴스의 onCreate() 메소드에서 컨텍스트를 static 필드인 mContext에 저장하고, getContext()와 같은 static 메소드를 만들어 이 필드를 반환합니다. 예를 들어 다음과 같습니다:

 

This is how it should look:

이렇게 보여야 합니다:
public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}

 

Now you can use: App.getContext() whenever you want to get a context, and then getResources() (or App.getContext().getResources()).

이제 App.getContext()를 사용하여 언제든지 context를 가져올 수 있으며, 그 다음 getResources() (또는 App.getContext().getResources())를 사용할 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

My Kotlin solution is to use a static Application context:

제 코틀린 해결 방법은 정적 Application 컨텍스트를 사용하는 것입니다:
class App : Application() {
    companion object {
        lateinit var instance: App private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

 

And the Strings class, that I use everywhere:

그리고 모든 곳에서 사용하는 Strings 클래스는 다음과 같습니다.
object Strings {
    fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
        return App.instance.getString(stringRes, *formatArgs)
    }
}

 

So you can have a clean way of getting resource strings

이렇게 하면 리소스 문자열을 깔끔하게 가져올 수 있습니다.
Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")

 

Please don't delete this answer, let me keep one.

이 답변을 삭제하지 마십시오. 하나를 남겨주세요.

 

 

 

출처 : https://stackoverflow.com/questions/4391720/how-can-i-get-a-resource-content-from-a-static-context

반응형
댓글
공지사항
최근에 올라온 글