从设置 activity 更改整个 Android 应用程序活动的语言

Change language for whole Android application activities from Setting activity

我正在尝试构建一个非常简单的应用程序来测试多语言主题,该应用程序还应该能够识别设备的语言,而且还有一种方法可以将语言更改为另一种 activity .

我正在使用语言文件夹,因此如果用户语言适合其中一种受支持的语言,它将采用正确的语言。

当我尝试将其从 'Setting' activity 更改为 activity 时,问题就开始了。

我有一个包含支持语言的微调器,在选择新语言后,当前 activity 应该关闭并且两个活动的语言都应该更改。

我在网上看到了几个例子,但这里没有人帮助我。

这是我的 XML 代码(仅包含一个小程序和文本):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.MES.yo.ActLanguageSettings">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="@string/Choose_Language" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/change_language" />

    <Spinner
        android:id="@+id/spnlanguage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

这是更改语言的代码:

public void changeLang(String lang)
    {
        if (lang.equalsIgnoreCase(""))
         return;
        myLocale = new Locale(lang);
        saveLocale(lang);
        Locale.setDefault(myLocale);
        android.content.res.Configuration config = new android.content.res.Configuration();
        config.locale = myLocale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }

    private void saveLocale(String lang)
    {
        String langPref = "Language";
        SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(langPref, lang);
        editor.commit();
    }

对于每个 activity,我都调用 "onConfigurationChanged" 方法,如下所示:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    Locale locale = new Locale(GVC.getLanguage());
    newConfig.locale = locale;
    super.onConfigurationChanged(newConfig);
    Locale.setDefault(locale);
    getBaseContext().getResources().updateConfiguration(newConfig,getBaseContext().getResources().getDisplayMetrics());
}

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.MES.yo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="18" />

    <application
        android:name=".GlobalVarClass"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" 
            android:configChanges="locale">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActLanguageSettings"
            android:label="@string/title_activity_act_language_settings" 
            android:configChanges="locale">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.MES.MySperm.MainActivity" />
        </activity>
    </application>

</manifest>

这对我来说根本不起作用。

我也试过像这样更改语言:

public void setLocale(String lang) {
            GVC.setLanguage(lang);
            myLocale = new Locale(lang);
            Resources res = getResources();
            DisplayMetrics dm = res.getDisplayMetrics();
            Configuration conf = res.getConfiguration();
            conf.locale = myLocale;
            res.updateConfiguration(conf, dm);
            Intent refresh = new Intent(this, ActLanguageSettings.class);
            startActivity(refresh);
            finish();
    }

此处的语言已更改,但所有其他活动均未更改,是否有关于如何正确执行的经验法则?

尝试使用此代码更改语言...

                    Locale locale = new Locale("ar");
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    getBaseContext().getResources().updateConfiguration(config,
                            getBaseContext().getResources().getDisplayMetrics());
                    settings.edit().putString("locale", "ar").commit();
                    this.finish();
                    Intent refresh = new Intent(this, MainActivity.class);
                    startActivity(refresh);

并且在每个 activity 的 onCreate 和 Onresume 方法中你必须做这样的事情..

if (settings.getString("locale","").equals("en")) {
        Locale locale = new Locale("en");
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
        settings.edit().putString("locale", "en").commit();
    }

如果你想让@Rishad 的答案起作用,你必须在设置 contentView 之前执行此操作,我的意思是在下面所有活动的代码行之前'oncreate() 方法

setContentView(R.layout.your_layout_name);

如果你不想一次又一次地这样做,你可以在 Java class 中创建一个方法并在你的活动中调用它。 或者,您可以在适用于您所有活动的应用程序 class 中执行此操作。 制作一个新的 Java class 并用 Application

扩展它
public class MyApp extends Application

然后在 class 的创建中添加此代码并覆盖方法 onConfigurationChanged(Configuration newConfig) 这是此 class

的完整代码
package com.qemasoft.alhabibshop.app;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.util.Log;

import java.util.Locale;

import static com.qemasoft.alhabibshop.app.AppConstants.LANGUAGE_KEY;

/**
 * Created by Inzimam Tariq on 1/17/2018.
 */

public class MyApp extends Application {

    private Locale locale;
    private static Context context;

    public static Context getAppContext() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getBaseContext();

            changeLocale(context);

    }

    public void changeLocale(Context context) {
        Configuration config = context.getResources().getConfiguration();
        String lang = Preferences
                .getSharedPreferenceString(this, LANGUAGE_KEY, "ar");
        Log.e("MyApp", "language in MyApp = " + lang);
        if (!(config.locale.getLanguage().equals(lang))) {
            locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            Log.e("MyApp", "Inside if = " + lang);
            context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (locale != null) {
            newConfig.locale = locale;
            Locale.setDefault(locale);
            context.getResources().updateConfiguration(newConfig, context.getResources().getDisplayMetrics());
        }
    }

}

在你的项目中有这个 class 之后,在 MainActivity

中重写下面的方法
@Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }

现在一切正常:) 注意:不要忘记在清单中添加此应用程序class,在清单中找到以

开头的标签
<application
        android:name=".MyApp"

在这里替换您的应用程序 class 我的名字是 MyApp,所以我在清单中有它。

重要说明:此代码的唯一缺点是除非您重新启动应用程序,否则更改不会出现。

在您的基地 activity 或主要 activity 中使用此代码。

public static void switchLocal(Context context, String lcode, Activity activity) {
        if (lcode.equalsIgnoreCase(""))
            return;
        Resources resources = context.getResources();
        Locale locale = new Locale(lcode);
        Locale.setDefault(locale);
        android.content.res.Configuration config = new 
        android.content.res.Configuration();
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
//restart base activaty 
        activity.finish();
        activity.startActivity(activity.getIntent());
    }