📌  相关文章
📜  如何以编程方式更改Android中的整个应用程序语言?

📅  最后修改于: 2021-05-10 17:48:31             🧑  作者: Mango

Android 7.0(API级别24)为多语言用户提供支持,允许用户在设置中选择多个语言环境。语言环境对象代表特定的地理,政治或文化区域。需要这些语言环境执行任务的操作称为对语言环境敏感的操作,并使用该语言环境为用户量身定制信息。例如,显示数字是对语言环境敏感的操作,因此,应根据用户的本国地区,文化或国家/地区的约定对数字进行格式化。

例子

在此示例中,我们将创建一个简单的应用程序,其中用户可以选择所需的语言-英语印地语。这将更改整个应用程序的语言。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:创建资源文件

在此步骤中,我们需要为印地语创建一个字符串资源文件。转到应用程序> res>值>右键单击>新建>值资源文件,并将其命名为字符串。现在,我们必须从可用列表中选择限定词作为Locale,并从下拉列表中选择语言作为北印度语。下面是要执行的步骤的图片。

现在,在此资源文件字符串.xml(hi)中,将以下代码添加到代码段中。

XML

    GFG | Change App Language
    हिन्दी
    नमस्ते, जी यफ जी


XML

    GFG | Change App Language
    English
    Hi, GFG


XML
 
    #0F9D58 
    #16E37F 
    #03DAC5 


XML


      
    
    
  
    
    


Java
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;
  
import java.util.Locale;
  
public class LocaleHelper {
        private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
  
        // the method is used to set the language at runtime
        public static Context setLocale(Context context, String language) {
            persist(context, language);
  
            // updating the language for devices above android nougat
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return updateResources(context, language);
            }
            // for devices having lower version of android os
            return updateResourcesLegacy(context, language);
        }
  
        private static void persist(Context context, String language) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(SELECTED_LANGUAGE, language);
            editor.apply();
        }
  
        // the method is used update the language of application by creating
        // object of inbuilt Locale class and passing language argument to it
        @TargetApi(Build.VERSION_CODES.N)
        private static Context updateResources(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Configuration configuration = context.getResources().getConfiguration();
            configuration.setLocale(locale);
            configuration.setLayoutDirection(locale);
  
            return context.createConfigurationContext(configuration);
        }
  
  
        @SuppressWarnings("deprecation")
        private static Context updateResourcesLegacy(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Resources resources = context.getResources();
  
            Configuration configuration = resources.getConfiguration();
            configuration.locale = locale;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale);
            }
  
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
  
            return context;
        }
    }


Java
import androidx.appcompat.app.AppCompatActivity;
  
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
    TextView messageView;
    Button btnHindi, btnEnglish;
    Context context;
    Resources resources;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // referencing the text and button views
        messageView = (TextView) findViewById(R.id.textView);
        btnHindi = findViewById(R.id.btnHindi);
        btnEnglish = findViewById(R.id.btnEnglish);
  
        // setting up on click listener event over the button
        // in order to change the language with the help of 
          // LocaleHelper class
        btnEnglish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "en");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
        btnHindi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "hi");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
    }
}


在英语的默认字符串.xml文件中,添加以下行。

XML格式


    GFG | Change App Language
    English
    Hi, GFG

在继续之前,让我们添加一些颜色属性以增强应用程序栏。转到应用程序> res>值> colors.xml并添加以下颜色属性。

XML格式

 
    #0F9D58 
    #16E37F 
    #03DAC5 
 

步骤3:为应用程序创建布局文件

在这一步中,我们将为我们的应用程序创建一个布局。转到应用程序> res>布局> activity_main.xml,然后添加两个TextView,一个用于消息,一个用于所选语言,以及一个ImageView用于drop_down图标。下面是为activity_main.xml文件提供的代码段。

XML格式



      
    
    
  
    
    

步骤4:创建LocaleHelper类

现在,我们将创建一个Locale Helper类。此类包含所有有助于在运行时进行语言切换的功能。转到应用程序> Java >程序包>右键单击并创建一个新的Java类,并将其命名为LocaleHelper 。下面是LocaleHelper类的代码段。

Java

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;
  
import java.util.Locale;
  
public class LocaleHelper {
        private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
  
        // the method is used to set the language at runtime
        public static Context setLocale(Context context, String language) {
            persist(context, language);
  
            // updating the language for devices above android nougat
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return updateResources(context, language);
            }
            // for devices having lower version of android os
            return updateResourcesLegacy(context, language);
        }
  
        private static void persist(Context context, String language) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(SELECTED_LANGUAGE, language);
            editor.apply();
        }
  
        // the method is used update the language of application by creating
        // object of inbuilt Locale class and passing language argument to it
        @TargetApi(Build.VERSION_CODES.N)
        private static Context updateResources(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Configuration configuration = context.getResources().getConfiguration();
            configuration.setLocale(locale);
            configuration.setLayoutDirection(locale);
  
            return context.createConfigurationContext(configuration);
        }
  
  
        @SuppressWarnings("deprecation")
        private static Context updateResourcesLegacy(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Resources resources = context.getResources();
  
            Configuration configuration = resources.getConfiguration();
            configuration.locale = locale;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale);
            }
  
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
  
            return context;
        }
    }

步骤5:使用MainActivity。 Java文件

在此步骤中,我们将实现Java代码以在字符串.xml文件之间切换以使用各种语言。首先,我们将初始化所有视图,并在“警报”对话框中设置单击行为,以借助LocalHelper类选择所需的语言。以下是MainActivity的代码段。 Java类。

Java

import androidx.appcompat.app.AppCompatActivity;
  
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
    TextView messageView;
    Button btnHindi, btnEnglish;
    Context context;
    Resources resources;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // referencing the text and button views
        messageView = (TextView) findViewById(R.id.textView);
        btnHindi = findViewById(R.id.btnHindi);
        btnEnglish = findViewById(R.id.btnEnglish);
  
        // setting up on click listener event over the button
        // in order to change the language with the help of 
          // LocaleHelper class
        btnEnglish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "en");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
        btnHindi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "hi");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
    }
}

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!