【Android】ユーザーが選択した言語に応じてアプリの表示言語を切り替える方法
このチュートリアルでは、ユーザーがスピナー(Spinner)で言語を選択した際に、アプリ全体の表示言語を動的に切り替える方法を解説します。LocaleオブジェクトとConfigurationを活用することで、端末本体の言語設定を変更しなくても、アプリ内の文字列リソースだけを別の言語に差し替えることができます。
実装手順
ステップ1:新規プロジェクトの作成
Android Studioで新しいプロジェクトを作成します。「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。
ステップ2:レイアウトファイルの編集
res/layout/activity_main.xml に以下のコードを追加します。言語選択用のSpinnerと、翻訳後の文字列を表示するTextViewを中央に配置しています。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity"> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <TextView android:id="@+id/string" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/thank_you" android:textSize="24sp" android:layout_centerInParent="true" android:layout_below="@id/spinner"/> </RelativeLayout>
ステップ3:MainActivity.java の実装
src/MainActivity.java に以下のコードを追加します。
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
Locale locale;
String currentLanguage = "en", currentLang;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentLanguage = getIntent().getStringExtra(currentLang);
spinner = findViewById(R.id.spinner);
List<String> list = new ArrayList<>();
list.add("Select Language");
list.add("English");
list.add("Español");
list.add("Français");
list.add("Hindi");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
break;
case 1:
setLocale("en");
break;
case 2:
setLocale("es");
break;
case 3:
setLocale("fr");
break;
case 4:
setLocale("hi");
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setLocale(String localeName) {
if (!localeName.equals(currentLanguage)) {
locale = new Locale(localeName);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this,
MainActivity.class);
refresh.putExtra(currentLang, localeName);
startActivity(refresh);
} else {
Toast.makeText(MainActivity.this, "Language
already selected!", Toast.LENGTH_SHORT).show();
}
}
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}処理のポイントはsetLocale()メソッドです。選択された言語コードからLocaleオブジェクトを生成し、ResourcesのConfigurationを更新することで、アプリ内のリソースが指定した言語に切り替わります。その後、Intentでアクティビティを再起動し、変更後の言語で画面を再描画しています。同じ言語が選択された場合はトーストで通知する仕組みになっています。
ステップ4:各言語用のstrings.xmlを作成
values-es(スペイン語)、values-fr(フランス語)、values-hi(ヒンディー語)フォルダをres配下に作成し、それぞれ以下のstrings.xmlを追加します。
values-hi/strings.xml
<resources> <string name="app_name">Sample</string> <string name="thank_you">धन्यवाद</string> </resources>
values-fr/strings.xml
<resources> <string name="app_name">Sample</string> <string name="thank_you">Je vous remercie</string> </resources>
values-es/strings.xml
<resources> <string name="app_name">Sample</string> <string name="thank_you">Gracias</string> </resources>
strings.xml(デフォルト:英語)
<resources> <string name="app_name">Sample</string> <string name="thank_you">Thank you</string> </resources>
ステップ5:AndroidManifest.xml の記述
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端末をパソコンに接続しているものとして説明を進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。接続したモバイルデバイスを選択して実行すると、端末に以下のような初期画面が表示されます。


補足:より新しい実装方法について
本記事で紹介しているres.updateConfiguration()は、現在では非推奨(deprecated)となっています。Android 13(APIレベル33)以降ではシステム標準の「アプリごとの言語設定」機能が提供されており、AppCompat 1.6.0以上を利用している場合はAppCompatDelegate.setApplicationLocales()を呼び出すだけで、よりシンプルかつ推奨された形で言語切り替えを実装できます。また、localeConfig属性を活用すれば、端末のシステム設定画面からもアプリの言語を変更できるようになります。新規開発の場合は、こちらの最新の手法を採用することをおすすめします。
-
【Android】5秒間のユーザー非アクティブ(無操作)を検出する方法を解説
はじめに 本記事では、Androidアプリでユーザーが5秒間何も操作しなかったこと(非アクティブ状態)を検出する方法を、サンプルコードとともに解説します。 鍵となるのは、Activityクラスに標準で用意されているonUserInteraction()コールバックです。このメソッドはタップやスワイプなど、ユーザーが画面を操作するたびに呼び出されるため、Handlerと組み合わせることで「最後の操作からの経過時間」を簡単に計測できます。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要事項を入力して、
-
Androidスマホでアプリのアイコンを変更する方法|Nova Launcherと専用アプリの使い方
Android OSの最大の魅力は、その高いカスタマイズ性にあります。端末に入れるアプリの選択から、インターフェース全体、画面遷移エフェクト、外観、さらにはアイコンに至るまで、ほぼすべてを自由に変更できます。もし今のスマホの見た目に飽きてしまったら、思い切ってイメージチェンジしてみましょう。テーマの変更、新しい壁紙の設定、クールなトランジション効果やアニメーションの追加、カスタムランチャーの導入、デフォルトアイコンをおしゃれなものに置き換えるなど、Androidはユーザーインターフェースを変えることで、古い端末をまるで新品のように生まれ変わらせることができるのです。 アプリのアイコンを変更