source

컨텍스트 또는 액티비티 외부 getString

itover 2023. 1. 25. 08:33
반응형

컨텍스트 또는 액티비티 외부 getString

★★★★★★★★★★★★★★★★★★★★★★★★★를 찾았습니다R.string하드코드된 문자열이 코드에 들어가지 않게 하는 것은 매우 훌륭합니다.또한 어플리케이션 내 모델과 함께 작업하여 출력을 생성하는 유틸리티 클래스에서 계속 사용하고 싶습니다.예를 들어, 이 경우 액티비티 외부의 모델에서 이메일을 생성합니다.

또는 외부에서 사용할 수 있습니까? 현재 활동에는 합격할 수 있지만 불필요할 것 같습니다.틀렸으면 정정해 주세요!

편집: 를 사용하지 않고 리소스에 액세스할 수 있습니까?Context

네, 'Context'를 사용하지 않고 리소스에 액세스할 수 있습니다.

다음을 사용할 수 있습니다.

Resources.getSystem().getString(android.R.string.somecommonstuff)

...고정 상수 선언에서도 응용 프로그램의 모든 위치를 확인할 수 있습니다.안타깝게도 시스템 리소스만 지원합니다.

로컬 리소스에 대해서는 이 솔루션을 사용하십시오.그것은 사소한 것이 아니라 효과가 있다.

문자열 수 있는 은 " " "를 하는 것입니다.Context (예:)Activity ★★★★★★★★★★★★★★★★★」Service이 경우는, 통상, 발신자에게 콘텍스트의 패스만을 요구합니다.

»MyApplication)Application:

public static Resources resources;

»MyApplication의 »onCreate:

resources = getResources();

이제 응용 프로그램의 모든 위치에서 이 필드를 사용할 수 있습니다.

##독특한 접근법

App.getRes().getString(R.string.some_id)

앱의 모든 곳에서 사용할 수 있습니다(Util 클래스, 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 getRes() {
        return res;
    }

}

) [이름()]에 이름 필드 추가manifest.xml <application붙이다

<application
        android:name=".App"
        ...
        >
        ...
    </application>

이제 가도 좋아요.App.getRes().getString(R.string.some_id)앱 내 어디에나 있습니다.

BTW, 기호를 찾을 수 없는 오류의 원인 중 하나는 IDE가 안드로이드를 가져왔기 때문일 수 있습니다.당신의 수업 대신 수업.Import Android를 변경하기만 하면 됩니다.R; your.namespace를 Import합니다.R;

다른 클래스에서 문자열을 표시하기 위한 2가지 기본 사항:

//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);
}

액티비티에서 사용하는 클래스가 있고 해당 클래스의 resource에 액세스할 수 있도록 하려면 컨텍스트를 클래스에서 개인 변수로 정의하고 컨스트럭터에서 초기화할 것을 권장합니다.

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);

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

하면 할 수 거예요.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"
    >

뭔가 잘못된 점이 있으면 알려주세요.감사합니다. : )

Kotlin에서 를 수행하려면 응용 프로그램을 확장하는 클래스를 만든 후 해당 컨텍스트를 사용하여 코드 내의 리소스를 호출합니다.

앱 클래스는 다음과 같습니다.

 class App : Application() {
    override fun onCreate() {
        super.onCreate()
        context = this
    }

    companion object {
        var context: Context? = null
            private set
    }
}

AndroidManifest.xml에서 응용 프로그램 클래스를 선언합니다(매우 중요).

<application
        android:allowBackup="true"
        android:name=".App" //<--Your declaration Here
        ...>
        <activity
            android:name=".SplashActivity"  android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity"/>
    </application>

문자열 파일에 액세스하려면 다음 코드를 사용합니다.

App.context?.resources?.getText(R.string.mystring)

정적 값을 저장하는 진부한 솔루션이 마음에 들지 않아 조금 더 길지만 테스트할 수 있는 깔끔한 버전을 생각해냈다.

가능한 방법 2가지를 찾았습니다.

  1. context.resources를 매개 변수로 문자열 리소스를 원하는 클래스에 전달합니다.꽤 간단합니다.param으로 전달할 수 없는 경우 setter를 사용합니다.

예.

data class MyModel(val resources: Resources) {
    fun getNameString(): String {
        resources.getString(R.string.someString)
    }
}
  1. 데이터 바인딩을 사용합니다(단, fragment/액티비티가 필요합니다).

읽기 전에:이 버전에서는Data binding

XML-

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="someStringFetchedFromRes"
        type="String" />
</data>

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@{someStringFetchedFromRes}" />
</layout>

액티비티 / 플래그먼트 -

val binding = NameOfYourBinding.inflate(inflater)
binding.someStringFetchedFromRes = resources.getString(R.string.someStringFetchedFromRes)

모델의 필드를 기준으로 텍스트를 변경해야 하는 경우도 있습니다.따라서 해당 모델도 데이터 바인딩할 수 있으며, 활동/조각이 모델에 대해 알고 있으므로 값을 가져온 다음 이를 기반으로 문자열을 데이터 바인딩할 수 있습니다.

컨텍스트 또는 액티비티 외부에서 getString Outside를 사용하는 경우 getstring() 메서드에 액세스할 수 있도록 컨스트럭터 또는 메서드 파라미터에 컨텍스트가 있어야 합니다.특히 fragment에서는 getActivity() 또는 getContext()가 늘 값을 제공하지 않는지 확인해야 합니다.fragment내의 getActivity() 또는 getContext()로부터의 늘을 회피하려면 , 다음의 순서를 실행합니다.변수를 선언합니다.

Context mContext;

fragment의 onAttach 메서드와 onDetach 메서드를 덮어씁니다.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

getString() 메서드를 사용하고 있는mContext 를 사용합니다.예:

        Toast.makeText(mContext,  mContext.getString(R.string.sample_toast_from_string_file), Toast.LENGTH_SHORT).show();

Kotlin: 완벽한 결정 02.03.2021


  • App Compat Activity(앱
  • Companion 객체

액티비티 코드:

class MainActivity : AppCompatActivity() {

    companion object {
        lateinit var instance: AppCompatActivity
            private set
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        instance = this
    }
}

AnyWhere에서 리소스 가져오기:

val text = MainActivity.instance.getString(R.string.task_1)

P.S Vel_daN: 당신이 하는 일이 좋아요.

나는 사용했다getContext().getApplicationContext().getString(R.string.nameOfString);저는 좋아요.

언급URL : https://stackoverflow.com/questions/4253328/getstring-outside-of-a-context-or-activity

반응형