수색…


통화

Currency currency = Currency.getInstance("USD");
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setCurrency(currency);
format.format(10.00);

Android 앱에 번역 추가

모든 새로운 언어에 대해 다른 strings.xml 파일을 만들어야합니다.

  1. res 폴더를 마우스 오른쪽 버튼으로 클릭하십시오.
  2. 새로 만들기리소스 파일 값 선택
  3. 사용 가능한 한정자에서 로케일을 선택하십시오.
  4. 다음 버튼 (>>)을 클릭하십시오.
  5. 언어 선택
  6. 파일 이름을 strings.xml로 지정하십시오 .

strings.xml

<resources>
    <string name="app_name">Testing Application</string>
    <string name="hello">Hello World</string>
</resources>

strings.xml (안녕)

<resources>
    <string name="app_name">परीक्षण आवेदन</string>
    <string name="hello">नमस्ते दुनिया</string>
</resources>

프로그래밍 방식으로 언어 설정하기 :

public void setLocale(String locale) // Pass "en","hi", etc.
{
    myLocale = new Locale(locale);
    // Saving selected locale to session - SharedPreferences.
    saveLocale(locale);
    // Changing locale.
    Locale.setDefault(myLocale);
    android.content.res.Configuration config = new android.content.res.Configuration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocale(myLocale);
    } else {
        config.locale = myLocale;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        getBaseContext().createConfigurationContext(config);
    } else {
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
}

위의 함수는 strings.xml 에서 참조되는 텍스트 필드를 변경합니다. 예를 들어 다음과 같은 두 가지 텍스트 뷰가 있다고 가정합니다.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/app_name"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

그런 다음 로케일을 변경 한 후 app_namehello 갖는 언어 문자열이 그에 따라 변경됩니다.

"res"폴더 아래의 자원 디렉토리 유형

각기 다른 유형의 리소스를 현지화해야 할 때, 각각은 안드로이드 프로젝트 구조에 자체 홈이 있습니다. 다음은 \res 디렉토리 아래에 배치 할 수있는 여러 디렉토리입니다. 각 디렉토리에있는 자원 유형은 아래 표에 설명되어 있습니다.

예배 규칙서 자원 유형
애니메이터/ 속성 애니메이션을 정의하는 XML 파일.
anim / 트윈 애니메이션을 정의하는 XML 파일. (속성 애니메이션도이 디렉토리에 저장할 수 있지만 애니메이터 / 디렉토리는 두 가지 유형을 구별하기 위해 속성 애니메이션에 우선합니다.)
색깔/ 색상의 상태 목록을 정의하는 XML 파일. 색상 상태 목록 자원을 참조하십시오.
드로어 블 / "다음과 같은 드로어 블 리소스 하위 유형으로 컴파일되는 비트 맵 파일 (.png, .9.png, .jpg, .gif) 또는 XML 파일 : Bitmap files - Nine-Patches (re-sizable bitmaps) - State lists - Shapes - Animation drawables - Other drawables - "
밉맵 / 다른 실행기 아이콘 밀도의 파일을 그릴 수 있습니다. 밉맵 / 폴더가있는 실행 프로그램 아이콘 관리에 대한 자세한 내용은 프로젝트 개요 관리를 참조하십시오.
형세/ 사용자 인터페이스 레이아웃을 정의하는 XML 파일. 레이아웃 리소스를 참조하십시오.
메뉴/ 옵션 메뉴, 컨텍스트 메뉴 또는 하위 메뉴와 같은 응용 프로그램 메뉴를 정의하는 XML 파일 Menu Resource를 참조하십시오.
노골적인/ 원시 형식으로 저장하는 임의의 파일. 원시 InputStream을 사용하여 이러한 리소스를 열려면 리소스 ID (R.raw.filename)로 Resources.openRawResource ()를 호출합니다.
그러나 원본 파일 이름과 파일 계층에 대한 액세스가 필요하면 assets / 디렉토리 (res / raw / 대신)에 일부 리소스를 저장하는 것이 좋습니다. 애셋 내의 파일 /에는 리소스 ID가 주어지지 않으므로 AssetManager 만 사용하여 읽을 수 있습니다.
값 / 문자열, 정수, 색상, 스타일 및 테마와 같은 간단한 값을 포함하는 XML 파일
xml / Resources.getXML ()을 호출하여 런타임에 읽을 수있는 임의의 XML 파일입니다. 검색 가능한 구성과 같이 여기에 다양한 XML 구성 파일을 저장해야합니다.

"res"디렉토리 아래의 각 폴더에 대한 구성 유형 및 한정자 이름

res 폴더 아래의 각 자원 디렉토리 (위의 예에 나열되어 있음)는 각 configuration-type 에 대해 다른 qualifier-values 접미사로 붙은 비슷한 이름의 디렉토리에 포함 된 다양한 변형을 가질 수 있습니다.

``우리의 안드로이드 프로젝트에서 흔히 볼 수있는 다른 접미사 값이 붙은 디렉토리의 변형 예 :

  • 드로어 블 /
  • drawable-en /
  • drawable-fr-rCA /
  • drawable-en-port /
  • drawable-en-notouch-12key /
  • drawable-port-ldpi /
  • drawable-port-notouch-12key /

모든 다른 구성 유형 및 안드로이드 리소스에 대한 한정자 값의 포괄적 인 목록 :

구성 한정어 값
MCC 및 MNC 예 :
mcc310
mcc310-mnc004
mcc208-mnc00
기타
언어 및 지역 예 :
fr
en-rUS
fr-rFR
fr-rCA
레이아웃 방향 ldrtl
LDT
smallestWidth swdp
예 :
sw320dp
sw600dp
sw720dp
사용 가능한 너비 wdp
w720dp
w1024dp
사용 가능한 높이 HDP
h720dp
h1024dp
화면 크기 작은
표준
화면 측면
notlong
라운드 스크린 일주
notround
화상 설명회 포트
나라
UI 모드
책상
텔레비전
어플라이언스 와치
야간 모드
밤에는
화면 픽셀 밀도 (dpi) ldpi
mdpi
hdpi
xhdpi
xxhdpi
xxxhdpi
nodpi
tvdpi
anydpi
터치 스크린 유형 건들지 말것
손가락
키보드 가용성 키 노출
열쇠 숨겨진
keyssoft
기본 텍스트 입력 방법 안돼
쿼티
12 키
탐색 키 사용 가능 여부 아직 공개되지 않은
네비게이션
기본 비 터치 방식의 탐색 방법 비 유적
dpad
트랙볼
바퀴
플랫폼 버전 (API 수준) 예 :
v3
v4
v7

프로그래밍 방식으로 안드로이드 응용 프로그램의 로케일 변경

위의 예제에서는 응용 프로그램의 리소스를 지역화하는 방법을 이해합니다. 다음 예제는 장치가 아니라 응용 프로그램 내에서 응용 프로그램 로캘을 변경하는 방법을 설명합니다. 응용 프로그램 로켈 만 변경하려면 다음 로켈 유틸리티를 사용할 수 있습니다.

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.ContextThemeWrapper;

import java.util.Locale;

/**
 * Created by Umesh on 10/10/16.
 */
public class LocaleUtils {

    private static Locale mLocale;

    public static void setLocale(Locale locale){
        mLocale = locale;
        if(mLocale != null){
            Locale.setDefault(mLocale);
        }
    }

    public static void updateConfiguration(ContextThemeWrapper wrapper){
        if(mLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            Configuration configuration = new Configuration();
            configuration.setLocale(mLocale);
            wrapper.applyOverrideConfiguration(configuration);
        }
    }

    public static void updateConfiguration(Application application, Configuration configuration){
        if(mLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1){
            Configuration config = new Configuration(configuration);
            config.locale = mLocale;
            Resources res = application.getBaseContext().getResources();
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }
    }

    public static void updateConfiguration(Context context, String language, String country){
        Locale locale = new Locale(language,country);
        setLocale(locale);
        if(mLocale != null){
            Resources res = context.getResources();
            Configuration configuration = res.getConfiguration();
            configuration.locale = mLocale;
            res.updateConfiguration(configuration,res.getDisplayMetrics());
        }
    }




    public static String getPrefLangCode(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString("lang_code","en");
    }

    public static void setPrefLangCode(Context context, String mPrefLangCode) {

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putString("lang_code",mPrefLangCode);
        editor.commit();
    }

    public static  String getPrefCountryCode(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString("country_code","US");
    }

    public static void setPrefCountryCode(Context context,String mPrefCountryCode) {

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putString("country_code",mPrefCountryCode);
        editor.commit();
    }
}

사용자가 선호하는 로케일을 Application 클래스에서 초기화하십시오.

public class LocaleApp extends Application{

    @Override
    public void onCreate() {
        super.onCreate();

        LocaleUtils.setLocale(new Locale(LocaleUtils.getPrefLangCode(this), LocaleUtils.getPrefCountryCode(this)));
        LocaleUtils.updateConfiguration(this, getResources().getConfiguration());
    }
}

또한 기본 활동을 작성하고이 활동을 다른 모든 활동으로 확장하여 다음과 같이 응용 프로그램의 로케일을 한 위치에서만 변경할 수 있어야합니다.

public abstract class LocalizationActivity extends AppCompatActivity {

    public LocalizationActivity() {
        LocaleUtils.updateConfiguration(this);
    }

    // We only override onCreate
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

}

주 : 항상 생성자에서 로케일을 초기화하십시오.

이제 다음과 같이 LocalizationActivity를 사용할 수 있습니다.

public class MainActivity extends LocalizationActivity {

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

    }
}

참고 : 프로그래밍 방식으로 응용 프로그램의 로캘을 변경하면 로캘 변경의 영향을 받기 위해 작업을 다시 시작해야합니다.이 솔루션을 제대로 사용하려면 응용 프로그램의 공유 환경 설정에서 로캘을 사용하십시오. android:name=".LocaleApp" in 당신 Manifest.xml.

때로는 린트 검사기가 릴리스 빌드를 작성하라는 프롬프트를 표시합니다. 이러한 문제를 해결하려면 아래 옵션을 따르십시오.

먼저:

일부 문자열에 대해서만 번역을 비활성화하려면 다음 속성을 기본 string.xml에 추가하십시오.

<string name="developer" translatable="false">Developer Name</string>

둘째:

다음과 같이 리소스 파일 add following 속성에서 누락 된 모든 번역 무시 string 파일의 tools 네임 스페이스의 무시 특성입니다.

<?xml version="1.0" encoding="utf-8"?>
<resources
  xmlns:tools="http://schemas.android.com/tools"
  tools:ignore="MissingTranslation" >
http://stackoverflow.com/documentation/android/3345/localization-with-resources-in-android#
  <!-- your strings here; no need now for the translatable attribute -->

</resources>

제삼:

번역 할 수없는 문자열을 비활성화하는 또 다른 방법

http://tools.android.com/recent/non-translatablestrings

번역하지 않아야 할 리소스가 많은 경우 donottranslate.xml 파일에 배치하고 lint는 번역 불가능한 리소스 모두를 고려합니다.

네번째:

리소스 파일에 로켈을 추가 할 수도 있습니다

<resources
xmlns:tools="http://schemas.android.com/tools"
    tools:locale="en" tools:ignore="MissingTranslation">

app / build.gradle에서 lint에 대한 번역 누락 확인을 사용 중지 할 수도 있습니다.

lintOptions {
        
        disable 'MissingTranslation'
    }


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow