App 내 전환 언어 설명
(본 사례 는 Data-bingding 모드 를 사 용 했 기 때문에 저 는 더 이상 걱정 하지 않 아 도 됩 니 다.findView By 가 Id 가 안 됩 니 다.하하,농담 입 니 다)
먼저 예시 도 를 올 립 니 다.
코드 구현:
레이아웃 파일(Data-bing 모드)은 두 줄 의 텍스트 입 니 다.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tnnowu.android.switchlanguage.MainActivity">
<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/title"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="@+id/descTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/titleTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="@string/desc"
android:textSize="20sp" />
</RelativeLayout>
</layout>
예 를 들 어 오른쪽 상단 에 Menu 가 있 는 것 을 볼 수 있 습 니 다.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/language_english"
android:orderInCategory="100"
android:title="@string/menu_english" />
<item
android:id="@+id/language_simplified_chinese"
android:orderInCategory="100"
android:title="@string/menu_simplified_chinese" />
<item
android:id="@+id/language_turkish"
android:orderInCategory="100"
android:title="@string/menu_turkish" />
<item
android:id="@+id/language_japanese"
android:orderInCategory="100"
android:title="@string/menu_japanese" />
</menu>
(다 국어 인 만큼 N 개의 strings 가 있어 야 한다)이 사례 에서 나 는 네 가지 언어 를 만 들 었 다.
알 겠 습 니 다.Menu 의 레이아웃 을 다 썼 습 니 다.다음은 Menu 기능 을 실현 하 는 것 입 니 다.Menu 를 실현 하 는 것 은 두 가지 코드 입 니 다.하 나 는 onCreate Options Menu 이 고 다른 하 나 는 onOptions ItemSelected 입 니 다.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.language_english) {
updateViews("en");
} else if (id == R.id.language_simplified_chinese) {
updateViews("zh");
} else if (id == R.id.language_turkish) {
updateViews("tr");
} else if (id == R.id.language_japanese) {
updateViews("ja");
}
return super.onOptionsItemSelected(item);
}
예언 전환 시 인터페이스의 변 화 를 실현 하기 위해 updateViews()방법 을 사용자 정의 할 수 있 습 니 다.
private void updateViews(String languageCode) {
Context context = LocaleHelper.setLocale(this, languageCode);
Resources resources = context.getResources();
mBinding.titleTextView.setText(resources.getString(R.string.title));
mBinding.descTextView.setText(resources.getString(R.string.desc));
setTitle(resources.getString(R.string.toolbar_title));
}
언어 판단 클래스 를 발표 합 니 다 LocaleHelper
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}
public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
persist(context, language);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
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();
}
@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);
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;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
마지막 으로 해 야 할 일 은 애플 리 케 이 션 클래스 를 사용자 정의 하여 애플 리 케 이 션 의 기본 언어 를 설정 하 는 것 입 니 다(물론 이 애플 리 케 이 션 을 Manifest 에 적용 해 야 합 니 다).
public class BaseApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
}
}
이 사례 는 앱 내 언어 전환 코드 의 양 이 많 지 않 고 알 기 쉬 우 며 스 팸 코드 가 없다 는 것 을 실현 한다.예시 코드 다운로드 주소:앱 내 전환 언어
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
빈 Jetpack Compose 앱 템플릿 정리themes.xml 및 colors.xml이 없는 단순하고 깨끗한 빈 Jetpack Compose 앱 예제입니다. 순수한 Jetpack Compose 앱의 경우 기술적으로 Android 보기 시스템용인 themes....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.