String.xml 에서 문자열 읽어 오기

개배박발불지은만자·2024년 3월 27일

android 에서 resouce의 문자열을 읽는 법

내가 기존에 쓰던법

val appid = context.resources.getString(R.string.APP_ID) 

새로 바꾼법

// context 의 확장함수

// 사용될 인수의 debug 모드와 release 모드의 회신값 id 를 Pair 로 인수로 사용한다.
val AD_BANNER_ID = Pair(R.string.AD_BANNER_ID_DEBUG,R.string.AD_BANNER_ID_RELEASE )

fun Context.resString( id:Pair<Int,Int> ):String
= this.resources.getString(if (BuildConfig.DEBUG) id.first else id.second)

context의 확장함수르로 resString이라는 함수를 만들고 그 함수에 id에 Pair 형으로

// 호출부
// 이미 선언된 값을 사용하는 예
context.resString(AD_BANNER_ID)

// 혹은 직접 Pair<Int,Int> 형으로 인계하는 예
context.resString( R.string.AD_BANNER_ID_DEBUG to R.string.AD_BANNER_ID_RELEASE)

0개의 댓글