You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中如何使用Spinner切换应用语言

在Android Kotlin中用Spinner实现应用语言切换

1. 准备多语言资源文件

首先为目标语言创建对应的资源文件夹:

  • 英文:values-en,内部创建strings.xml
  • 中文简体:values-zh-rCN,内部创建strings.xml

每个strings.xml使用相同的key,对应不同语言的文本:

<!-- values/strings.xml(默认语言) -->
<resources>
    <string name="app_name">LanguageSwitchDemo</string>
    <string name="select_language">Select Language</string>
    <string name="english">English</string>
    <string name="chinese">Chinese</string>
</resources>
<!-- values-zh-rCN/strings.xml -->
<resources>
    <string name="app_name">语言切换示例</string>
    <string name="select_language">选择语言</string>
    <string name="english">英文</string>
    <string name="chinese">中文</string>
</resources>

2. 布局中添加Spinner

在Activity布局文件(如activity_main.xml)中加入Spinner组件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/languageSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/select_language" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/app_name" />

</LinearLayout>

3. 实现Spinner选择与语言切换逻辑

在Activity的Kotlin代码中,完成Spinner初始化、选择监听及核心语言切换逻辑:

class MainActivity : AppCompatActivity() {

    private lateinit var languageSpinner: Spinner
    private val languageOptions = listOf(
        "en" to getString(R.string.english),
        "zh" to getString(R.string.chinese)
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        languageSpinner = findViewById(R.id.languageSpinner)
        setupSpinner()
    }

    private fun setupSpinner() {
        // 设置Spinner适配器
        val adapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            languageOptions.map { it.second }
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        languageSpinner.adapter = adapter

        // 默认选中当前语言
        val currentLang = getCurrentLanguage()
        languageSpinner.setSelection(languageOptions.indexOfFirst { it.first == currentLang })

        // 监听选择事件
        languageSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selectedLang = languageOptions[position].first
                if (selectedLang != currentLang) {
                    switchLanguage(selectedLang)
                    recreate() // 重启Activity生效
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }

    // 获取当前应用语言
    private fun getCurrentLanguage(): String {
        return resources.configuration.locale.language
    }

    // 核心:切换语言并保存设置
    private fun switchLanguage(languageCode: String) {
        val locale = Locale(languageCode)
        Locale.setDefault(locale)

        val config = resources.configuration
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            config.setLocales(LocaleList(locale))
        } else {
            config.setLocale(locale)
        }
        resources.updateConfiguration(config, resources.displayMetrics)

        // 持久化语言设置
        getSharedPreferences("AppSettings", MODE_PRIVATE)
            .edit()
            .putString("selected_lang", languageCode)
            .apply()
    }

    // 启动时恢复保存的语言
    override fun attachBaseContext(newBase: Context) {
        val savedLang = newBase.getSharedPreferences("AppSettings", MODE_PRIVATE)
            .getString("selected_lang", "en") ?: "en"
        val wrappedContext = wrapContext(newBase, savedLang)
        super.attachBaseContext(wrappedContext)
    }

    // 包装上下文切换语言
    private fun wrapContext(context: Context, langCode: String): Context {
        val locale = Locale(langCode)
        val config = context.resources.configuration.apply {
            setLocale(locale)
        }
        return context.createConfigurationContext(config)
    }
}

关键注意事项

  • Android 12及以上版本需使用setLocales替代setLocale以兼容系统语言规则
  • 语言切换后必须重启Activity,才能让所有界面文本更新
  • 多Activity应用建议将语言恢复逻辑放到BaseActivity中,避免重复代码

内容的提问来源于stack exchange,提问作者Kelvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:05:34