컨텍스트 또는 활동 외부의 getString
R.string
하드 코드 된 문자열을 코드에서 유지하는 것이 매우 훌륭 하다는 것을 알았으며 응용 프로그램의 모델과 함께 작동하여 출력을 생성하는 유틸리티 클래스에서 계속 사용하고 싶습니다. 예를 들어,이 경우 활동 외부의 모델에서 이메일을 생성합니다.
또는 getString
밖에서 사용할 수Context
Activity
있습니까? 현재 활동을 통과 할 수 있다고 생각하지만 불필요한 것 같습니다. 내가 틀렸다면 정정 해주세요!
편집 : 우리는 사용 하지 않고 리소스에 액세스 할 수 있습니까 Context
?
예, 컨텍스트를 사용하지 않고도 리소스에 액세스 할 수 있습니다
당신이 사용할 수있는:
Resources.getSystem().getString(android.R.string.somecommonstuff)
... 정적 상수 선언에서도 응용 프로그램의 모든 곳에서. 불행히도 시스템 리소스 만 지원 합니다 .
로컬 리소스의 경우이 솔루션을 사용 하십시오 . 사소한 것이 아니지만 작동합니다.
불행히도 문자열 리소스에 액세스 할 수있는 유일한 방법은 Context
( Activity
또는 Service
)를 사용하는 것입니다. 이 경우에 일반적으로 한 일은 단순히 호출자가 컨텍스트를 전달하도록 요구하는 것입니다.
에서 MyApplication
확장 Application
:
public static Resources resources;
에서 MyApplication
의 ' onCreate
:
resources = getResources();
이제 애플리케이션의 어느 곳에서나이 필드를 사용할 수 있습니다.
BTW, symbol not found 오류 의 원인 중 하나는 IDE가 android.R을 가져 왔기 때문일 수 있습니다. 당신 대신 하나의 수업. 가져 오기 android.R을 변경하십시오 . your.namespace.R 을 가져 오려면;
따라서 다른 클래스에서 문자열을 볼 수있는 두 가지 기본 사항 :
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
독특한 접근법
App.getRes().getString(R.string.some_id)
이것은 응용 프로그램의 모든 곳에서 작동합니다. ( Util class, Dialog, Fragment 또는 앱의 모든 클래스 )
(1) Application
수업을 만들거나 편집하십시오 (있는 경우) .
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static App mInstance;
private static Resources res;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getResourses() {
return res;
}
}
(2) 이름 필드를 manifest.xml
<application
태그에 추가하십시오 .
<application
android:name=".App"
...
>
...
</application>
이제 잘 가세요. App.getRes().getString(R.string.some_id)
앱 어디에서나 사용하십시오 .
활동에 사용하는 클래스가 있고 해당 클래스의 리소스에 액세스하려는 경우 컨텍스트를 클래스의 개인 변수로 정의하고 생성자에서 초기화하는 것이 좋습니다.
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
당신의 활동에서 수업의 순간을 만들기 :
MyClass m=new MyClass(this);
이를 applicationContext
통해 어디서나 액세스 할 수 있어야 applicationContext
합니다. Toast
, getString()
, sharedPreferences
, 등
싱글 톤 :
package com.domain.packagename;
import android.content.Context;
/**
* Created by Versa on 10.09.15.
*/
public class ApplicationContextSingleton {
private static PrefsContextSingleton mInstance;
private Context context;
public static ApplicationContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized ApplicationContextSingleton getSync() {
if (mInstance == null) mInstance = new PrefsContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
Application
서브 클래스 에서 싱글 톤을 초기화하십시오 :
package com.domain.packagename;
import android.app.Application;
/**
* Created by Versa on 25.08.15.
*/
public class mApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationContextSingleton.getInstance().initialize(this);
}
}
내가 틀리지 않으면 응용 프로그램 컨텍스트에 대한 후크를 제공합니다. 호출하십시오. ApplicationContextSingleton.getInstance.getApplicationContext();
응용 프로그램을 닫을 때 언제든지 지울 필요가 없습니다. 어쨌든 함께 진행됩니다.
AndroidManifest.xml
이 Application
서브 클래스 를 사용 하도록 업데이트하십시오 :
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.domain.packagename"
>
<application
android:allowBackup="true"
android:name=".mApplication" <!-- This is the important line -->
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:icon="@drawable/app_icon"
>
여기에 잘못된 것이 있으면 알려주십시오. 감사합니다. :)
Khemraj의 답변에서 가장 좋은 방법 :
앱 클래스
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
매니페스트 선언
<application
android:name=".App"
...>
</application>
상수 클래스
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
사용
textView.text = Localizations.info
컨텍스트 와 활동 없이 다음과 같은 것을 사용하는 것이 좋습니다 .
Resources.getSystem().getString(R.string.my_text)
다음은 MainActivity에서 아래와 같이 컨텍스트에 대한 정적 변수를 만듭니다.
public static Context mContext;
그리고 onCreate ()에서 mContext를 이것으로 초기화하십시오.
mContext = this;
그런 다음 컨텍스트에 액세스하려는 파일에서
private Context context = MainActivity.mContext;
이제 다음과 같은 방법으로 문자열 리소스를 얻을 수 있습니다.
String myString = context.getResources().getString(R.string.resource_id);
나는 getContext().getApplicationContext().getString(R.string.nameOfString);
그것을 위해 일했다.
참고 URL : https://stackoverflow.com/questions/4253328/getstring-outside-of-a-context-or-activity
'Programing' 카테고리의 다른 글
변수 이름이 종종 문자 'm'으로 시작하는 이유는 무엇입니까? (0) | 2020.04.15 |
---|---|
문자열 구분 기호로 문자열을 어떻게 나눌 수 있습니까? (0) | 2020.04.15 |
Vim의 자동 완성 (0) | 2020.04.15 |
Emacs에서 열린 파일의 이름을 바꾸려면 어떻게해야합니까? (0) | 2020.04.15 |
jQuery를 사용하여 알파벳순으로 목록을 정렬하려면 어떻게해야합니까? (0) | 2020.04.15 |