如何在不重新创建活动的情况下在运行时更改语言

问题描述

我使用以下代码将语言从认更改为选定语言。但是我无法使用所选语言更新我的片段/活动中的视图,例如 TextView。以编程方式显示所选语言。

我的应用程序也是 potrait onConfigurationChanged() 即使我在清单文件中声明 android:configChanges="layoutDirection|locale" 也没有调用

注意:我不想 recreate() 我的活动。

1.在attachBaseContext中使用BaseActivity来设置locale语言并为所有Activity扩展这个Activity

open class  BaseAppCompactActivity() : AppCompatActivity() {

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(LocaleHelper.onAttach(newBase))

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }
}

2.使用 Application attachBaseContext 和 onConfigurationChanged 来设置语言环境。

public class MyApplication extends Application {

   private static MyApplication application;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public static MyApplication getApplication() {
        return application;
    }

    /**
     * overide to change local sothat language can be chnaged from android device  nogaut and above
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    /*** also handle chnage  language if  device language chnaged **/

        super.onConfigurationChanged(newConfig);

    }

3. 使用 Locale Helper 处理语言更改,此方法适用于所有设备

object LocaleHelper {

fun onAttach(context: Context,defaultLanguage: String): Context {
    return setLocale(context,defaultLanguage)
}

fun setLocale(context: Context,language: String): Context {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        updateResources(context,language)
    } else updateResourcesLegacy(context,language)

}


@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context,language: String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)

    val configuration = context.getResources().getConfiguration()
    configuration.setLocale(locale)
    configuration.setLayoutDirection(locale)

    return context.createConfigurationContext(configuration)
}




    private fun updateResourcesLegacy(context: Context,language: String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)

    val resources = context.getResources()
}

解决方法

看看:https://developer.android.com/guide/topics/resources/localization

它将允许您创建将根据设备默认语言显示的字符串资源文件。