Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidでプログラムからアプリの言語を動的に変更する方法【実装例つき】

この記事では、Androidアプリの表示言語をプログラムから動的に切り替える方法を解説します。サンプルとして、アプリ起動時に表示言語をブルガリア語へ変更する実装を段階的に紹介します。

手順1:新規プロジェクトを作成する

Android Studioを開き、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトを作成してください。

手順2:レイアウトファイル(res/layout/activity_main.xml)にコードを追加する

まず、画面中央にテキストを表示するシンプルなレイアウトを用意します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="30dp"
        android:textStyle="bold"
        android:textColor="@color/colorPrimary"
        android:layout_centerInParent="true"/>
</RelativeLayout>

手順3:MainActivity.javaにロケール切替処理を追加する

次に、ConfigurationLocaleを使ってアプリのロケールを変更するメソッドを実装します。Android 4.2(API 17)以降ではconfig.setLocale()を使用し、それ以前のバージョンではconfig.localeに直接代入する点がポイントです。

import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAppLocale("bg");
        setContentView(R.layout.activity_main);
    }
    private void setAppLocale(String localeCode){
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){
            config.setLocale(new Locale(localeCode.toLowerCase()));
        } else {
            config.locale = new Locale(localeCode.toLowerCase());
        }
        resources.updateConfiguration(config, dm);
    }
}

手順4:多言語リソースファイル(values-bg/strings.xml)を作成する

「res」フォルダを右クリックし、「New」→「File」を選択して、values-bg/strings.xmlという名前のファイルを作成します。ここにはブルガリア語の文字列リソースを定義します。

<resources>
    <string name="app_name">Sample</string>
    <string name="hello_world">дравей свят</string>
</resources>

手順5:AndroidManifest.xmlにコードを追加する

マニフェストファイルは以下のようになります。特別な権限は不要ですが、アクティビティの宣言が正しく行われていることを確認してください。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して結果を確認する

それでは、アプリを実行してみましょう。実機のAndroidスマートフォンがPCに接続されているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択すると、端末の画面に以下のように表示されます。

Androidでプログラムからアプリの言語を動的に変更する方法【実装例つき】

Androidでプログラムからアプリの言語を動的に変更する方法【実装例つき】

補足:最新のAndroidでの推奨手法

上記の方法は幅広いバージョンで動作する古典的な手法です。一方、Android 13(API 33)以降ではOS標準の「アプリごとの言語設定」が導入されており、AndroidX AppCompat 1.6以上を使用している場合はAppCompatDelegate.setApplicationLocales()を呼び出すことで、より簡単かつ推奨された形で言語を切り替えられます。新しいプロジェクトでは、こちらの活用も検討するとよいでしょう。

  1. AndroidでGoogleアシスタントの言語を変更・追加する方法

    Googleの音声アシスタント「Googleアシスタント」は、英語以外にも多数の言語に対応しています。対応言語が豊富であることは、世界中の人々が自分の最も話しやすい言語でGoogleアシスタントとやり取りできることを意味します。 この記事では、Googleアシスタントの言語を変更する方法を詳しく解説します。 Googleアシスタントが対応している言語 Googleアシスタントは40以上の言語に対応しています。2014年の登場時と比べると、大幅な進化といえます。ただし、対応言語には利用上の制限がある点に注意が必要です。 現時点では、Googleアシスタントがサポートするすべての言語が、すべての地

  2. iPhoneでアプリごとに言語を変更する方法【iOS 13以降】

    以前のiPhoneでは、言語設定を変更できるのはシステム全体のみで、アプリ単位での切り替えはできませんでした。しかし、iOS 13からその常識が変わりました。過去1年半ほどの大型アップデートの中では見落とされがちな機能ですが、アプリごとに言語を設定できるオプションは非常に便利です。特に2つの言語を日常的に使い分けている方にとっては、知らないと損をするレベルの便利な隠れ機能といえます。この記事では、iPhone本体の言語設定はそのまま維持しながら、特定のアプリだけ言語を変更する方法を詳しく解説します。アプリの言語を変更する前に知っておきたいことアプリの言語を変更したい理由は人それぞれあると思いま