添加新的语言环境并在Android应用程序中强制使用语言环境(本地化)

Mix*_*lis 6 android localization android-studio

我尝试学习如何在android studio中编程,我目前正在第二篇关于如何通过本地化来改变语言的教程.当我尝试strings.xml在文件夹中创建第二个文件时,values_el它说我不能因为名称应该是唯一的.我尝试将原始strings.xml文件从values文件夹复制到新的values_el文件夹,我翻译邮件但没有任何反应.此外,我尝试右键单击原始strings.xml文件,我按下翻译选项,我从那里翻译,但没有任何反复.当我在手机中运行应用程序时,我尝试上述两种方式的语言都是英语.我的手机语言是希腊语,但我的程序字母是英文.

问题2.

首先为什么语言不会改变我的手机?第二种方法是在我打开它时通过按下按钮来改变我的应用程序的语言?我在谷歌游戏中玩的一些游戏可以选择在你开始游戏之前选择你的游戏.抱歉我的英语,如果你不明白我说的话请告诉我,所以我试着用谷歌翻译帮助更好地解释它.无论如何,谢谢你的时间.

那是我运行的代码

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_my"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/edit_message"   />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:onClick="testActivity" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

And*_*tel 8

为什么不通过IDE使用简单的方法?

  1. 打开你的strings.xml文件
  2. 单击Open Editor下面的链接

在此输入图像描述

  1. 通过选择这样添加要添加翻译的区域设置

在此输入图像描述

  1. 这将为您创建正确的文件,而无需担心文件名

  2. 你不需要打开每个strings.xml来放置本地化的字符串.从这个strings.xml编辑器中做到这一点.

转到第二个问题:本地应用程序将是设备设置中设备上选择的区域设置.如果你还没有本地化的设备区域会回落到主strings.xmlres/values.

要在应用中强制使用区域设置,而不考虑设备的区域设置:

在您的活动类中添加以下方法并将其调用 onCreate

private void setLanguageForApp(String language){

    String languageToLoad  = language; //pass the language code as param
    Locale locale;
    if(languageToLoad.equals("not-set")){
        locale = Locale.getDefault();
    }
    else {
        locale = new Locale(languageToLoad);
    }
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)