Android Studio: Activity 外で getString 使いたかった。

簡単な Activity 内での使い方メモ

文字列を格納するファイルのパス

res/values/strings.xml

文字列宣言

<string name="someText">SomeText</string>

使用例

getString(R.string.someText)

 

結局 Context をどっかにぶち込むか、Application で宣言して使えるようにしないといけないらしい。

こういうコードもあるみたいだけどシステムリソースしか使えないので、自分で定義したものはこの方法だと呼び出せない。

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

Context をぶち込む

class Test(context:Context){
    val context = context
    fun something(){
        context.getString(R.string.someText)
    }
}

Application 経由でアクセスする

import android.app.Application;
import android.content.res.Resources;

public class App:Application() {
    companion object{
        lateinit var res:Resources
    }
    override fun onCreate() {
        super.onCreate();
        res = resources;
    }

}
class Test{
   fun something(){
       App.res.getString(R.string.someText)
   }
}

おわり。

どっちもどっちな気がする。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA