【问题标题】:appLocale setting in android studioandroid studio中的appLocale设置
【发布时间】:2019-09-26 01:34:55
【问题描述】:

我已经创建了广播组,用户可以在其中选择他们想要的语言并将应用程序语言更改为所选语言,但我无法使用这些功能(不知道如何使用!)

我做了什么?

  1. 我做了settingsActivity
  2. 我添加了广播组
  3. 我写了setAppLocale函数
  4. 我已设置 onRadioButtonClicked 更改语言

代码

settingsActivity.java

package com.xxxxxx.xxxxx;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;

import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RadioButton;

import java.util.Locale;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }


    //locale settings
    public void setAppLocale(String localeCode) {
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            conf.setLocale(new Locale(localeCode.toLowerCase()));
        } else {
            conf.locale = new Locale(localeCode.toLowerCase());
        }

        res.updateConfiguration(conf, dm);
    }

    // application language switch
    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.radio_indo:
                if (checked)
                    setAppLocale("id");
                    break;
            case R.id.radio_english:
                if (checked)
                    setAppLocale("en");
                    break;
        }
    }

}

settings_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/settings">


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4sp"
            android:layout_marginRight="4sp"
            android:weightSum="3"
            android:gravity="center"
            android:orientation="horizontal">

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

            <RadioGroup
                    android:id="@+id/appLang"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:layout_marginTop="35dp"
                    android:layout_marginEnd="35dp"
                    android:layout_marginRight="35dp"
                    android:layout_marginStart="35dp"
                    android:layout_marginLeft="35dp"
                    android:orientation="horizontal">

                <TextView
                        android:id="@+id/applangtext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/applangtextstring" />

                <RadioButton
                        android:id="@+id/radio_indo"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:onClick="onRadioButtonClicked"
                        android:text="@string/indoLang" />

                <RadioButton
                        android:id="@+id/radio_english"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:onClick="onRadioButtonClicked"
                        android:text="@string/englishLang" />

            </RadioGroup>
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

问题

我需要在我的 java 文件中做两件事:

  1. 将当前语言无线电输入标记为已选择
  2. 当用户选择另一个单选按钮时进行更改

问题是我如何将onRadioButtonClicked 连接到 setAppLocale?以及按顺序返回当前语言onCreate 显示当前选择的语言?

更新

根据下面的答案,这是我添加的最新更新和额外文件。 但我的语言切换不起作用

settingsActivity.java

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Locale;

public class SettingsActivity extends AppCompatActivity {

    PrefManager prefManager; //added
    RadioButton radio_indo, radio_english; //added
    RadioGroup appLang; //added

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);

        //added
        prefManager = new PrefManager(this);

        radio_indo = findViewById(R.id.radio_indo);
        radio_english = findViewById(R.id.radio_english);
        appLang = findViewById(R.id.appLang);

        if (prefManager.getLanguage().equals("en")) {
            radio_english.setChecked(true);
        } else {
            radio_english.setChecked(true);
        }

        // application language switch (added)
        appLang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
                switch (checkId) {
                    case R.id.radio_indo:
                        prefManager.setLanguage("id");
                        // you need to restart or recreate your activity after locale change
                        break;
                    case R.id.radio_english:
                        prefManager.setLanguage("en");
                        // you need to restart or recreate your activity after locale change
                        break;
                }
            }
        });

    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }


    //locale settings
    public void setAppLocale(String localeCode) {
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            conf.setLocale(new Locale(localeCode.toLowerCase()));
        } else {
            conf.locale = new Locale(localeCode.toLowerCase());
        }

        res.updateConfiguration(conf, dm);
    }

     // removed my old function as new function added to onCreate

}

PrefManager.java添加类

import android.content.Context;
import android.content.SharedPreferences;

public class PrefManager {
    private SharedPreferences.Editor editor;
    private Context mContext;
    private SharedPreferences prefs;
    private final String LANGUAGE = "language";
    private final String PREF = "user_data";

    public PrefManager(Context mContext) {
        this.mContext = mContext;
    }

    public String getLanguage() {
        this.prefs = this.mContext.getSharedPreferences(PREF, 0);
        return this.prefs.getString(LANGUAGE, "en");
    }

    public void setLanguage(String language) {
        this.editor = this.mContext.getSharedPreferences(PREF, 0).edit();
        this.editor.putString(LANGUAGE, language);
        this.editor.apply();
    }
}

BaseActivity.java添加类

import android.content.Context;

import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;

/**
 * Created by nilesh on 20/3/18.
 */

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void attachBaseContext(Context newBase) {

        Locale newLocale;

        String lang = new PrefManager(newBase).getLanguage();

        if (lang.equals("en")) {
            newLocale = new Locale("en");
        } else {
            newLocale = new Locale(lang);
        }


        Context context = ContextWrapper.wrap(newBase, newLocale);
        super.attachBaseContext(context);
    }
}

settings_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/settings">


    <RadioGroup
            android:id="@+id/appLang"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="35dp"
            android:layout_marginLeft="35dp"
            android:layout_marginTop="90dp"
            android:layout_marginEnd="35dp"
            android:layout_marginRight="35dp"
            android:gravity="center"
            android:orientation="horizontal">

        <TextView
                android:id="@+id/applangtext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/applangtextstring" />

        <RadioButton
                android:id="@+id/radio_indo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/indoLang" />

        <RadioButton
                android:id="@+id/radio_english"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/englishLang" />

    </RadioGroup>
</RelativeLayout>

这就是我关于语言切换的全部内容。

PS-1:基于我应该添加的答案 cmets 中提供的解决方案 BaseActivity 作为我所有活动的延伸,但作为我所有的活动 是kotlin 不是java(settingsActivity 除外)我无法 添加它。

PS-2:即使没有得到翻译也是因为我无法添加 扩展至少我应该能够在我的 settingsActivity 是java 对吧?

知道为什么这个开关不起作用吗?

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    注意

    You can download source code from github repo

    将当前语言无线电输入标记为已选择

    然后您需要将您的语言环境更改标志/状态保存在 SharedPreferences

    示例代码按照以下步骤操作

    创建一个类名PrefManager

    import android.content.Context;
    import android.content.SharedPreferences;
    
    public class PrefManager {
        private SharedPreferences.Editor editor;
        private Context mContext;
        private SharedPreferences prefs;
        private final String LANGUAGE = "language";
        private final String PREF = "user_data";
    
        public PrefManager(Context mContext) {
            this.mContext = mContext;
        }
    
        public String getLanguage() {
            this.prefs = this.mContext.getSharedPreferences(PREF, 0);
            return this.prefs.getString(LANGUAGE, "en");
        }
    
        public void setLanguage(String language) {
            this.editor = this.mContext.getSharedPreferences(PREF, 0).edit();
            this.editor.putString(LANGUAGE, language);
            this.editor.apply();
        }
    }
    

    现在在您的settingsActivity.java 中添加以下代码/条件

    public class JavaActivity extends AppCompatActivity {
    
        PrefManager prefManager;
        RadioButton radio_indo, radio_english;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_java);
            prefManager = new PrefManager(this);
            radio_indo = findViewById(R.id.radio_indo);
            radio_english = findViewById(R.id.radio_english);
    
            if (prefManager.getLanguage().equals("en")) {
                radio_english.setChecked(true);
            } else {
                radio_english.setChecked(true);
            }
        }
    
    }
    

    当用户选择另一个单选按钮时进行更改

    • 当用户更改语言时,您需要更新它SharedPreferences
    • 更改区域设置后,您需要重新启动或重新创建活动

    注意:您应该使用RadioGroup.OnCheckedChangeListener() 而不是android:onClick="onRadioButtonClicked"

    示例代码

    public class JavaActivity extends AppCompatActivity {
    
        PrefManager prefManager;
        RadioButton radio_indo, radio_english;
        RadioGroup appLang;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_java);
            prefManager = new PrefManager(this);
    
            radio_indo = findViewById(R.id.radio_indo);
            radio_english = findViewById(R.id.radio_english);
            appLang = findViewById(R.id.appLang);
    
            if (prefManager.getLanguage().equals("en")) {
                radio_english.setChecked(true);
            } else {
                radio_english.setChecked(true);
            }
    
            appLang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
                    switch (checkId) {
                        case R.id.radio_indo:
                            prefManager.setLanguage("id");
                            // you need to restart or recreate your activity after locale change
                            break;
                        case R.id.radio_english:
                            prefManager.setLanguage("en");
                            // you need to restart or recreate your activity after locale change
                            break;
                    }
                }
            });
        }
    
    }
    

    请按照我之前的回答更改语言环境运行时

    https://stackoverflow.com/a/52270630/7666442

    【讨论】:

    • 嗨,谢谢你的回答,但我有一个非常愚蠢的问题,因为这是我第一次尝试使用 android studio,我应该在哪里创建这个 Create one class name PrefManager 以及我应该从 new -&gt; ? 中选择什么选项 :)对不起:D
    • @mafortis 没问题,请查看How To Create New Java Class in Android Studio
    • 嗨 :) ,抱歉,我没有得到这部分 Note : you should use RadioGroup.OnCheckedChangeListener() instead of android:onClick="onRadioButtonClicked" 我应该在哪里使用 RadioGroup.OnCheckedChangeListener() 在我的 xml 中?
    • @mafortis 每当您使用 RadioGroup 时,您都应该使用 OnCheckedChangeListener() 来获得选中 radioButton 检查此 How to set OnClickListener on a RadioButton in Android?
    • 嗨,它工作得很好,我希望有收音机组而不是按钮,但它也很好。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多