android studio 中的 appLocale 设置 [英] appLocale setting in android studio
问题描述
我创建了广播组,用户可以在其中选择他们想要的语言并将应用程序语言更改为所选语言,但我无法使用这些功能(不知道如何使用!)
我做了什么?
- 我已经做了
settingsActivity
- 我添加了广播组
- 我已经写了
setAppLocale
函数 - 我已将
onRadioButtonClicked
设置为更改语言
代码
settingsActivity.java
package com.xxxxxx.xxxxx;导入 android.content.res.Configuration;导入 android.content.res.Resources;导入 android.os.Build;导入 android.os.Bundle;导入 androidx.appcompat.app.ActionBar;导入 androidx.appcompat.app.AppCompatActivity;导入 androidx.preference.PreferenceFragmentCompat;导入 android.util.DisplayMetrics;导入 android.view.View;导入 android.widget.RadioButton;导入 java.util.Locale;公共类 SettingsActivity 扩展 AppCompatActivity {@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.settings_activity);getSupportFragmentManager().beginTransaction().replace(R.id.settings, new SettingsFragment()).犯罪();ActionBar actionBar = getSupportActionBar();如果(动作条!= null){actionBar.setDisplayHomeAsUpEnabled(true);}}公共静态类 SettingsFragment 扩展 PreferenceFragmentCompat {@覆盖public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {setPreferencesFromResource(R.xml.root_preferences, rootKey);}}//区域设置public void setAppLocale(String localeCode) {资源 res = getResources();DisplayMetrics dm = res.getDisplayMetrics();配置 conf = res.getConfiguration();如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {conf.setLocale(new Locale(localeCode.toLowerCase()));} 别的 {conf.locale = new Locale(localeCode.toLowerCase());}res.updateConfiguration(conf, dm);}//应用语言切换公共无效 onRadioButtonClicked(查看视图){//按钮现在是否被选中?布尔检查 = ((RadioButton) 视图).isChecked();//检查哪个单选按钮被点击开关(视图.getId()){案例 R.id.radio_indo:如果(选中)setAppLocale("id");休息;案例 R.id.radio_english:如果(选中)setAppLocale("en");休息;}}}
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/设置"><线性布局android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginEnd="4sp"机器人:layout_marginRight="4sp"机器人:weightSum =3"机器人:重力=中心"机器人:方向=水平"><线性布局android:layout_width="match_parent"android:layout_height="match_parent"机器人:方向=垂直"><广播集团android:id="@+id/appLang"android:layout_width="match_parent"android:layout_height="wrap_content"机器人:重力=中心"android:layout_marginTop="35dp"android:layout_marginEnd="35dp"机器人:layout_marginRight="35dp"android:layout_marginStart="35dp"android:layout_marginLeft="35dp"机器人:方向=水平"><文本视图android:id="@+id/applangtext"android:layout_width="wrap_content"android:layout_height="wrap_content"机器人:layout_weight="1"android:text="@string/applangtextstring"/><单选按钮android:id="@+id/radio_indo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="onRadioButtonClicked"android:text="@string/indoLang"/><单选按钮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 文件中做两件事:
- 将当前语言无线电输入标记为已选择
- 在用户选择另一个单选按钮时进行更改
<块引用>
问题是我如何将 onRadioButtonClicked
连接到setAppLocale
?以及按顺序返回当前语言 onCreate
显示当前选择的语言?
更新
根据下面的答案,这里是我的最新更新和我添加的额外文件.但我的语言切换不起作用
settingsActivity.java
import android.content.res.Configuration;导入 android.content.res.Resources;导入 android.os.Build;导入 android.os.Bundle;导入 androidx.appcompat.app.AppCompatActivity;导入 androidx.preference.PreferenceFragmentCompat;导入 android.util.DisplayMetrics;导入 android.view.View;导入 android.widget.RadioButton;导入 android.widget.RadioGroup;导入 java.util.Locale;公共类 SettingsActivity 扩展 AppCompatActivity {PrefManager prefManager;//添加RadioButton radio_indo, radio_english;//添加RadioGroup appLang;//添加@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.settings_activity);//添加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);} 别的 {radio_english.setChecked(true);}//应用程序语言切换(添加)appLang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@覆盖public void onCheckedChanged(RadioGroup radioGroup, int checkId) {开关(检查 ID){案例 R.id.radio_indo:prefManager.setLanguage("id");//您需要在区域设置更改后重新启动或重新创建您的活动休息;案例 R.id.radio_english:prefManager.setLanguage("en");//您需要在区域设置更改后重新启动或重新创建您的活动休息;}}});}公共静态类 SettingsFragment 扩展 PreferenceFragmentCompat {@覆盖public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {setPreferencesFromResource(R.xml.root_preferences, rootKey);}}//区域设置public void setAppLocale(String localeCode) {资源 res = getResources();DisplayMetrics dm = res.getDisplayMetrics();配置 conf = res.getConfiguration();如果 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {conf.setLocale(new Locale(localeCode.toLowerCase()));} 别的 {conf.locale = new Locale(localeCode.toLowerCase());}res.updateConfiguration(conf, dm);}//删除我的旧函数作为添加到 onCreate 的新函数}
PrefManager.java
添加类
import android.content.Context;导入 android.content.SharedPreferences;公共类 PrefManager {私有 SharedPreferences.Editor 编辑器;私有上下文 mContext;私有 SharedPreferences 首选项;private final String LANGUAGE =语言";private final String PREF = "user_data";公共偏好管理器(上下文 mContext){this.mContext = mContext;}公共字符串 getLanguage() {this.prefs = this.mContext.getSharedPreferences(PREF, 0);返回 this.prefs.getString(LANGUAGE, "en");}公共无效设置语言(字符串语言){this.editor = this.mContext.getSharedPreferences(PREF, 0).edit();this.editor.putString(LANGUAGE, 语言);this.editor.apply();}}
BaseActivity.java
添加类
import android.content.Context;导入 androidx.appcompat.app.AppCompatActivity;导入 java.util.Locale;/*** 由 nilesh 于 20/3/18 创建.*/公共类 BaseActivity 扩展 AppCompatActivity {@覆盖protected void attachBaseContext(Context newBase) {语言环境 newLocale;String lang = new PrefManager(newBase).getLanguage();如果(lang.equals(en")){newLocale = new Locale("en");} 别的 {newLocale = new Locale(lang);}上下文上下文 = 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/设置"><广播集团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"机器人:layout_marginRight="35dp"机器人:重力=中心"机器人:方向=水平"><文本视图android:id="@+id/applangtext"android:layout_width="wrap_content"android:layout_height="wrap_content"机器人:layout_weight="1"android:text="@string/applangtextstring"/><单选按钮android:id="@+id/radio_indo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/indoLang"/><单选按钮android:id="@+id/radio_english"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/englishLang"/></RadioGroup></RelativeLayout>
这就是我关于语言切换的全部内容.
<块引用>PS-1:基于我应该添加的回答评论中提供的解决方案BaseActivity
作为我所有活动的扩展,但作为我所有的活动是 kotlin
不是 java
(settingsActivity 除外)我无法添加它.
PS-2:即使没有得到翻译也是因为我无法添加至少扩展我应该能够在我的settingsActivity 是 java
对吗?
知道为什么这个开关不起作用吗?
注意
<块引用>将当前语言广播输入标记为选中
然后您需要在 SharedPreferences
示例代码请按照以下步骤操作
<块引用>创建一个类名PrefManager
import android.content.Context;导入 android.content.SharedPreferences;公共类 PrefManager {私有 SharedPreferences.Editor 编辑器;私有上下文 mContext;私有 SharedPreferences 首选项;private final String LANGUAGE =语言";private final String PREF = "user_data";公共偏好管理器(上下文 mContext){this.mContext = mContext;}公共字符串 getLanguage() {this.prefs = this.mContext.getSharedPreferences(PREF, 0);返回 this.prefs.getString(LANGUAGE, "en");}公共无效设置语言(字符串语言){this.editor = this.mContext.getSharedPreferences(PREF, 0).edit();this.editor.putString(LANGUAGE, 语言);this.editor.apply();}}
<块引用>
现在在您的 settingsActivity.java
public class JavaActivity extends AppCompatActivity {PrefManager prefManager;RadioButton radio_indo, radio_english;@覆盖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);} 别的 {radio_english.setChecked(true);}}}
<块引用>
当用户选择另一个单选按钮时进行更改
- 当用户更改语言时,您需要更新它
SharedPreferences
- 您需要在区域设置更改后重新启动或重新创建您的活动
注意:您应该使用 RadioGroup.OnCheckedChangeListener()
而不是 android:onClick="onRadioButtonClicked"
示例代码
public class JavaActivity extends AppCompatActivity {PrefManager prefManager;RadioButton radio_indo, radio_english;RadioGroup appLang;@覆盖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);} 别的 {radio_english.setChecked(true);}appLang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@覆盖public void onCheckedChanged(RadioGroup radioGroup, int checkId) {开关(检查 ID){案例 R.id.radio_indo:prefManager.setLanguage("id");//您需要在区域设置更改后重新启动或重新创建您的活动休息;案例 R.id.radio_english:prefManager.setLanguage("en");//您需要在区域设置更改后重新启动或重新创建您的活动休息;}}});}}
<块引用>
请按照我之前的回答更改语言环境运行时
https://stackoverflow.com/a/52270630/7666442
I have made radio group where user can select their desire language and app language changes to selected language but i am not able to use the functions (not sure how to!)
What I did?
- I've made
settingsActivity
- I've added radio group
- I've wrote
setAppLocale
function - I've set
onRadioButtonClicked
to change languages
Code
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>
Question
I need to make 2 things happen in my java file:
- Mark current language radio input as selected
- Make changes when user select another radio button
The question is how do I connect
onRadioButtonClicked
tosetAppLocale
? as well as return current languageonCreate
in order to show current language selected?
Update
Based on answer below here is my latest update and extra files that I've added. Yet my language switch doesn't work
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
added class
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
added class
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>
This is all I have regarding to language switch.
PS-1: based on provided solution in answer comments I should have add
BaseActivity
as extends in all my activites but as all my activities arekotlin
notjava
(except settingsActivity) I was not able to add it.PS-2: even if not getting translatations is because I couldn't add extends at very least I should be able to see translations in my settingsActivity which is
java
right?
Any idea why this switch doesn't work?
NOTE
You can download source code from github repo
Mark current language radio input as selected
Then you need to save your locale change flag/state inside SharedPreferences
SAMPLE CODE follow these steps
Create one class name
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();
}
}
Now add below code/ condition in your
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);
}
}
}
Make changes when user select another radio button
- When the user changes the language you need to update it
SharedPreferences
- You need to restart or recreate your activity after locale change
Note : you should use RadioGroup.OnCheckedChangeListener()
instead of android:onClick="onRadioButtonClicked"
SAMPLE CODE
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;
}
}
});
}
}
Please follow this my previous answer to change locale runtime
https://stackoverflow.com/a/52270630/7666442
这篇关于android studio 中的 appLocale 设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!