programing

안드로이드에서 string.xml의 값을 읽는 방법은 무엇입니까?

instargram 2023. 5. 22. 20:19
반응형

안드로이드에서 string.xml의 값을 읽는 방법은 무엇입니까?

나는 다음과 같은 대사를 썼습니다.

String Mess = R.string.mess_1 ;

문자열 값을 가져오지만 문자열을 반환하는 대신 정수 유형의 ID를 제공합니다.문자열 값을 얻으려면 어떻게 해야 합니까?문자열 값을 다음에서 언급했습니다.string.xml파일.

사용해 보세요.

String mess = getResources().getString(R.string.mess_1);

갱신하다

String string = getString(R.string.hello);

다음 중 하나를 사용할 수 있습니다.getString(int)또는getText(int)문자열을 검색합니다. getText(int)문자열에 적용된 리치 텍스트 스타일을 유지합니다.

참조: https://developer.android.com/guide/topics/resources/string-resource.html

활동 중:

this.getString(R.string.resource_name)

활동 중이 아니지만 컨텍스트에 액세스할 수 있는 경우:

context.getString(R.string.resource_name)
application.getString(R.string.resource_name)

사용 중인 항목:

String URL = Resources.getSystem().getString(R.string.mess_1);

참고로 strings.xml에 다음과 같은 문자열 배열을 만들 수도 있습니다.

<string-array name="tabs_names"> 
    <item>My Tab 1</item> 
    <item>My Tab 2</item>
</string-array>

활동을 통해 다음과 같은 참조 자료를 얻을 수 있습니다.

String[] tab_names = getResources().getStringArray(R.array.tab_names);
String tabname1=tab_names[0];//"My Tab 1"

향후 참조용으로만 제공됩니다.

String resources 설명서에는 다음과 같이 나와 있습니다.

getString(int) 또는 getText(int)를 사용하여 문자열을 검색할 수 있습니다. getText(int) will > 문자열에 적용된 리치 텍스트 스타일을 유지합니다.

솔루션 1

Context context;
String mess = context.getString(R.string.mess_1)

솔루션 2

String mess = getString(R.string.mess_1)

단편적으로, 당신은 사용할 수 있습니다.

getActivity().getString(R.id.whatever);

예를 들어 버튼에 문자열 값을 추가하려면 단순 사용

android:text="@string/NameOfTheString"

strings.xml에 정의된 텍스트는 다음과 같습니다.

 <string name="NameOfTheString">Test string</string>

세부 사항

  • 안드로이드 스튜디오 3.1.4
  • 코틀린 버전: 1.2.60

작업

  • 단회선 사용
  • 최소 코드
  • 컴파일러의 제안을 사용합니다.

1단계. 적용()

응용프로그램의 컨텍스트에 대한 링크 가져오기

class MY_APPLICATION_NAME: Application() {

    companion object {
        private lateinit var instance: MY_APPLICATION_NAME

        fun getAppContext(): Context = instance.applicationContext
    }

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

}

2단계. 확장자 추가

inline fun Int.toLocalizedString(): String = MY_APPLICATION_NAME.getAppContext().resources.getString(this)

사용.

strings.xml

<resources>
    <!-- .......  -->
    <string name="no_internet_connection">No internet connection</string>
    <!-- .......  -->
</resources>

문자열 값 가져오기:

val errorMessage = R.string.no_internet_connection.toLocalizedString()

결과.

여기에 이미지 설명 입력 여기에 이미지 설명 입력

strings.xml에 정의된 값을 직접 읽을 수 있습니다.

<resources>
    <string name="hello">Hello StackOverflow!</string>
</resources>

변수로 설정합니다.

String mymessage = getString(R.string.hello);

그러나 문자열을 뷰에 정의할 수 있습니다.

<TextView
    android:id="@+id/myTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"/>

사용하기 전에 컨텍스트 이름을 참조해야 합니다.getResources()안드로이드로.

String user=getApplicationContext().getResources().getString(R.string.muser);

OR

Context mcontext=getApplicationContext();

String user=mcontext.getResources().getString(R.string.muser);

다음 코드를 사용할 수 있습니다.

getText(R.string.mess_1);

기본적으로 getText() 메서드에 리소스 ID를 매개 변수로 전달해야 합니다.

사용할 수 있는 활동인 경우

getResources().getString(R.string.whatever_string_youWant);

활동에 참여하지 않은 경우 다음을 사용합니다.

getApplicationContext.getResource().getString(R.String.Whatever_String_you_want)

당신이 쓰는 동안R당신은 그것을 언급하고 있습니다.R.java이클립스에 의해 작성된 클래스, 사용getResources().getString()그리고 통과합니다.id내부에서 읽으려는 리소스의getString()방법.

예: String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

Jetpack Compose를 사용하는 경우 다음을 사용할 수 있습니다.

stringResource(R.string.yourstring)

**

나는 이 코드가 유익하기를 바랍니다.

**

String user = getResources().getString(R.string.muser); 

갱신하다

  • 사용할 수 있습니다.getString(R.string.some_string_id)둘 다 또는 둘 다
  • 사용할 수 있습니다.Context.getString(R.string.some_string_id)직접 액세스할 수 없는 경우getString()방법.맘에 들다Dialog.

문제는 액세스 권한이 없는 곳입니다. 예를 들어, 사용자 환경에 있는 방법과 같습니다.Util학생들

컨텍스트가 없는 아래 방법을 가정합니다.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

이제 당신은 합격할 것입니다.Context하고 이 방 및 사 변 수 로 매 개 의 용 법 로 ▁as 이getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

내가 하는 일은

public void someMethod(){
    ...
    App.getRes().getString(R.string.some_id)
}

뭐라고요? 당신의 앱 어디서든 사용하는 것은 매우 간단합니다!

여기 다음과 같은 장소에서 리소스에 액세스할 수 있는 Bonus 고유 솔루션이 있습니다.Util class.

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

}

에 이름 필드를 합니다.manifest.xml <application꼬리표를 달다

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

이제 당신은 가도 좋습니다.

getString(R.string).결과를 확인합니다.

String myString = getResources().getString(R.string.here_your_string_name);

이제 당신의 문자열이 myString에 복사되었습니다.그것이 당신에게 효과가 있기를 바랍니다.

언급URL : https://stackoverflow.com/questions/2183962/how-to-read-value-from-string-xml-in-android

반응형