사용자가 언어를 선택할 때 앱의 언어를 변경하는 방법은 무엇입니까?
앱에서 스페인어, 포르투갈어 및 영어의 세 가지 언어를 지원하고 싶습니다. 그리고 앱에서 언어를 선택하는 옵션을 제공합니다.
1) drawable-es, drawable-pt, drawable 3 개의 드로어 블 폴더.
2) 3 개의 값 폴더 values-es, values-pt, values. 언어에 따라 String.xml 값을 변경합니다.
언어를 선택할 수있는 imageView가 있습니다. 클릭하면 영어, 스페인어, 포르투갈어 옵션으로 구성된 메뉴가 열립니다.
이 코드로 옵션 선택시 앱 내부에 로케일을 설정했습니다.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.en:
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in English !", Toast.LENGTH_LONG).show();
break;
case R.id.pt:
Locale locale2 = new Locale("pt");
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;
getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in Portugal !", Toast.LENGTH_LONG).show();
break;
case R.id.es:
Locale locale3 = new Locale("es");
Locale.setDefault(locale3);
Configuration config3 = new Configuration();
config3.locale = locale3;
getBaseContext().getResources().updateConfiguration(config3, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in Spain !", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
Manifest- android : configChanges = "locale" 에서 선언했습니다 .
작동하지만 문제가 있습니다.
문제:-
1) 언어 선택시 언어 선택 이미지로 구성된 화면은 변경되지 않고 다른 화면은 변경됩니다.
2) 방향 변경 후 휴대 전화의 로케일에 따라 앱 복원 언어.
웹 페이지 발췌 : http://android.programmerguru.com/android-localization-at-runtime/
사용자가 언어 목록에서 선택하면 앱의 언어를 간단하게 변경할 수 있습니다. 로케일을 문자열 (영어의 경우 'en', 힌디어의 경우 'hi'와 같이)으로 허용하는 아래와 같은 방법을 사용하고 앱의 로케일을 구성하고 언어 변경 사항을 반영하도록 현재 활동을 새로 고칩니다. 적용한 로케일은 수동으로 다시 변경할 때까지 변경되지 않습니다.
public void setLocale(String lang) {
Locale 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, AndroidLocalize.class);
finish();
startActivity(refresh);
}
다음 패키지를 가져 왔는지 확인하십시오.
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
활동에 매니페스트 추가 android : configChanges = "locale | orientation"
android:configChanges="locale"
매니페스트에서 제거 하여 활동을 다시로드하거나 onConfigurationChanged
메서드를 재정의해야 합니다.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// your code here, you can use newConfig.locale if you need to check the language
// or just re-set all the labels to desired string resource
}
all above code is perfect but only one this is missing mine was not working just because the language was not mentioned in the config file
defaultConfig {
resConfigs "en", "hi", "kn"
}
after that, all languages started running
Good solutions explained pretty well here. But Here is one more.
Create your own CustomContextWrapper
class extending ContextWrapper
and use it to change Locale setting for the complete application. Here is a GIST with usage.
And then call the CustomContextWrapper
with saved locale identifier e.g. 'hi'
for Hindi language in activity lifecycle method attachBaseContext
. Usage here:
@Override
protected void attachBaseContext(Context newBase) {
// fetch from shared preference also save the same when applying. Default here is en = English
String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
super.attachBaseContext(SnapContextWrapper.wrap(newBase, language));
}
Those who getting the version issue try this code ..
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 activity
activity.finish();
activity.startActivity(activity.getIntent());
}
Udhay's sample code works well. Except the question of Sofiane Hassaini and Chirag SolankI, for the re-entrance, it doesn't work. I try to call Udhay's code without restart the activity in onCreate() , before super.onCreate(savedInstanceState);. Then it is OK! Only a little problem, the menu strings still not changed to the set Locale.
public void setLocale(String lang) { //call this in onCreate()
Locale 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, AndroidLocalize.class);
//startActivity(refresh);
//finish();
}
'program story' 카테고리의 다른 글
Clojure 개발자가 피해야 할 일반적인 프로그래밍 실수 (0) | 2020.09.01 |
---|---|
Maven이 컴파일하고 빌드 jar에 포함 할 추가 소스 디렉토리를 추가하는 방법은 무엇입니까? (0) | 2020.09.01 |
Eclipse에서 작업 태그를 현재 프로젝트로 제한하는 방법은 무엇입니까? (0) | 2020.09.01 |
Razor If / Else 조건부 연산자 구문 (0) | 2020.09.01 |
Django Rest Framework-뷰 이름 "user-detail"을 사용하여 하이퍼 링크 된 관계에 대한 URL을 확인할 수 없습니다. (0) | 2020.09.01 |