LoginSignup
5
5

More than 3 years have passed since last update.

Androidでアプリ内のLocaleを変更せずに他言語リソースを取得する

Last updated at Posted at 2020-09-19

はじめに

Androidで言語を切り替える場合、下記のようにActivityのattachBaseContextでlocaleを設定するのが一般的です。(API 25でupdateConfigurationはdeprecatedとなり、createConfigurationContextの利用が推奨されています。)

ですが、一つの画面に複数の言語リソースを表示したい場合や言語切替時にActivityをrecreateしたくない場合、この方法は使えません。今回は一時的に変更できるようにする方法をメモしときます。

MainActivity.kt
override fun attachBaseContext(base: Context) {
    val locale = Locale.ENGLISH
    val res = resources
    val config = Configuration(res.configuration)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocales(LocaleList(locale))
    } else {
        config.setLocale(locale)
    }
    super.attachBaseContext(base.createConfigurationContext(config))
}

やり方

やり方はとても簡単です。attachBaseContextでlocaleを変更したcontextを返さなければいいだけです。
まずは、言語を切替やすくするためにcreateLocalizedContextという拡張関数を作ります。

ContextExtention.kt
fun Context.createLocalizedContext(locale: Locale): Context {
    val res = resources
    val config = Configuration(res.configuration)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocales(LocaleList(locale))
    } else {
        config.setLocale(locale)
    }
    return createConfigurationContext(config)
}

リソースファイルは日本語(default)と英語を用意。

values/strings.xml
<string name="hello_world">こんにちは 世界</string>
values-en/strings.xml
<string name="hello_world">hello world</string>

利用方法は下記の通り。簡単に切り替えられました。

MainActivity.kt
    var localizedContext = applicationContext.createLocalizedContext(Locale.ENGLISH)
    print(localizedContext.getString(R.string.hello_world))
    // hello world

    localizedContext = applicationContext.createLocalizedContext(Locale.JAPANESE)
    print(localizedContext.getString(R.string.hello_world))
    // こんにちは 世界
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5