티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
getString Outside of a Context or Activity
컨텍스트 또는 액티비티 외부에서 getString 사용하기
문제 내용
I've found the R.string
pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity.
R.string은 코드에서 하드코딩된 문자열을 제거하는 데 매우 유용하며, 출력을 생성하기 위해 응용 프로그램의 모델과 함께 작동하는 유틸리티 클래스에서 계속 사용하고 싶습니다. 예를 들어, 이 경우에는 액티비티 외부의 모델에서 이메일을 생성합니다.
Is it possible to use getString
outside a Context
or Activity
? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong!
컨텍스트 또는 액티비티 외부에서 getString을 사용할 수 있습니까? 현재 액티비티를 전달할 수 있다고 생각하지만 불필요한 것 같습니다. 내가 틀렸다면 정정해주세요!
Edit: Can we access the resources without using Context
?
편집: 컨텍스트를 사용하지 않고 리소스에 액세스할 수 있습니까?
높은 점수를 받은 Solution
Yes, we can access resources without using `Context`
예, 'Context'를 사용하지 않고 리소스에 액세스할 수 있습니다.
You can use:
다음을 사용할 수 있습니다.
Resources.getSystem().getString(android.R.string.somecommonstuff)
... everywhere in your application, even in static constants declarations. Unfortunately, it supports the system resources only.
... 정적 상수 선언에서도 응용 프로그램의 모든 곳에 적용됩니다. 안타깝게도 시스템 리소스만 지원합니다.
For local resources use this solution. It is not trivial, but it works.
로컬 리소스의 경우 이 솔루션을 사용하십시오. 그것은 사소한 것이 아니라 효과가 있다.
가장 최근 달린 Solution
The best approach from the response of Khemraj:
Khemraj의 응답에서 가장 좋은 접근법은 다음과 같습니다.
App class
앱 클래스
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Declaration in the manifest
매니페스트의 선언
<application
android:name=".App"
...>
</application>
Constants class
상수 클래스
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Using
사용.
textView.text = Localizations.info
출처 : https://stackoverflow.com/questions/4253328/getstring-outside-of-a-context-or-activity
'개발 > 안드로이드' 카테고리의 다른 글
메시징을 사용한 액티비티와 서비스 간 커뮤니케이션 예제 (0) | 2022.12.06 |
---|---|
시스템 오버레이 윈도우(항상 다른 앱 위에) 만들기 (0) | 2022.12.05 |
WebView에서 파일 업로드하기 (0) | 2022.12.05 |
RecyclerView에 헤더뷰 넣기 (0) | 2022.12.05 |
Activity has leaked window 문제 수정하기 (0) | 2022.12.05 |