본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 안드로이드 다국어 지원

by teamnova 2021. 5. 27.

여러 국가를 대상으로 하는 앱을 만들떄, 해당 국가의 언어에 맞게 여러 언어를 제공해줘야 할 필요가 있습니다.

이번 예제에서는 어떻게 다국어를 지원해줄 수 있는지 알아보도록 하겠습니다. 

 

여러 나라에세 서비스를 출시 할려면, 해당 나라가 쓰는 언어들을 지원해 줘야 합니다. 이번 시간에는 kotlin으로 앱 내에서 언어 설정을 변경하는 방법을 알아보도록 하겠습니다.

 

저번 자바에서 사용했던 화면을 그대로 사용하겠습니다. (자바로 언어 설정을 바꾸는 방법은 이 포스팅을 참고해주세요.)

 

activity_translation.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TranslationActivity">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="232dp"
        android:text="언어 설정"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/sample_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="@string/sample_text"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/sample_text">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="20dp"
            android:text="한글" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="20dp"
            android:text="영어" />
    </RadioGroup>


</androidx.constraintlayout.widget.ConstraintLayout>

화면 구성은 라디오 버튼과 바뀐 언어를 표시할 TextView로 이루어져 있습니다. 한글 버튼을 클릭시 '샘플 문장'이 보일 것이며 영어 버튼을 클릭하면 'Sample Sentence' 문구가 보이게 될 것입니다.

 

Default Language 문구 작성

설정에 따라 Text의 내용이 바뀌기 위해서는 res -> values 폴더의 string.xml 파일에 앱 내에서 사용될 문구들을 작성해줘야 합니다. 작성 언어는 앱의 기본 언어로 설정할 언어로 작성해주시면 됩니다. 이 예제에서는 한국어가 기본 언어이기 때문에 리소스 sample_text에  '샘플 문장'이라고 적었습니다.

 

<resources>
    <string name="app_name">StickodeJAVA2</string>
    
    -- 앱 내에서 사용될 문구
    <string name="sample_text">샘플 문장</string>
</resources>

Translations Editor 열기

기본 언어 문구를 작성했다면, 지원할 언어를 추가해 주도록 합시다. Translations Editor를 통해 해당 문구

res -> values 폴더의 string.xml 파일을 마우스 우클릭한 후 아래와 같이 Open Translation Editor를 선택해 Translations Editor를 열어줍니다. 

왼쪽 상단에 있는 지구 모양 버튼을 클릭 한 다음, 추가하고 싶은 언어를 선택해줍니다. 저는 English로 선택 했습니다.

언어를 추가하게 되면 아래 이미지와 같이 오른쪽에 추가한 언어가 생성됩니다. 그 후, 번역되길 원하는 문구를 적어줍니다. 여기선 Sample Sentence라고 적어주었습니다.

 위의 작업을 통해, 앱 언어가 한글일 경우 '샘플 문장'이, 영어일 경우 'Semple Sentence'가 보이도록 해줄 수 있습니다.

이제 실제로 앱 언어를 설정하는 방법을 알아보도록 하겠습니다.

 

코드 작성

TranslationActivity.kt

 

사용자의 선택에 따라 언어를 바꾸기 위해서는 다음 두가지 객체를 사용해야 합니다. Locale 과 Configure 객체인데요. 이 객체에 대해서는 안드로이드 개발자 문서를 참고하시면 좋을 거 같습니다.

developer.android.com/reference/java/util/Locale

 

Locale  |  Android 개발자  |  Android Developers

 

developer.android.com

developer.android.com/reference/android/content/res/Configuration

 

Configuration  |  Android 개발자  |  Android Developers

 

developer.android.com

구현은 스틱코드를 등록하시면 언제든 쉽게 하실 수 있습니다.

 

 

 

package com.example.stickcodekotlin

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.widget.RadioButton
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class TranslationActivity : AppCompatActivity() {
    private lateinit var korean: RadioButton
    private lateinit var english: RadioButton
    private lateinit var language_code: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_translation)

        korean = findViewById(R.id.radioButton)
        english = findViewById(R.id.radioButton2)

        // 저장된 언어 코드를 불러온다.
        val sharedPreferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE)
        val language = sharedPreferences.getString("My_Lang", "")
        if (language != null) {
            Log.d("로그", "language :"+language)
            language_code = language
        }

        // 저장된 언어코드에 따라 라디오 버튼을 체크해준다.
        if(language_code.equals("en") || language_code.equals("")){
            english.setChecked(true);
        }else{
            korean.setChecked(true);
        }

        //한국어 라디오 버튼 변경
        korean.setOnClickListener {
            setLocate("ko")
            recreate()
        }
        // 영어 라디오 버튼 변경
        english.setOnClickListener {
            setLocate("en")
            recreate()
        }

    }

    //Locale 객체를 생성특정 지리적, 정치적 또는 문화적 영역을 나타냅니다.
    private fun setLocate(Lang: String) {
        Log.d("로그", "setLocate")
        val locale = Locale(Lang) // Local 객체 생성. 인자로는 해당 언어의 축약어가 들어가게 됩니다. (ex. ko, en)
        Locale.setDefault(locale) // 생성한 Locale로 설정을 해줍니다.

        val config = Configuration() //이 클래스는 응용 프로그램이 검색하는 리소스에 영향을 줄 수 있는
                                    // 모든 장치 구성 정보를 설명합니다.

        config.setLocale(locale) // 현재 유저가 선호하는 언어를 환경 설정으로 맞춰 줍니다.
        baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics)

        // Shared에 현재 언어 상태를 저장해 줍니다.
        val editor = getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
        editor.putString("My_Lang", Lang)
        editor.apply()
    }
}

stickode.com/detail.html?no=2132

 

스틱코드

 

stickode.com

 

결과 영상