Strings.xmlについての勉強
Android では、文字列を res/values/strings.xml の中に定義します。
例として下記のような画面を作成していきます。
画面上で使用する文字列は、「タイトル」「開始」「終了」です。
まずはテストするためのプロジェクトの作成です。
プロジェクト名は適当にTest01としました。
次に、パッケージ・エクスプローラーのres>values>strings.xmlを開きます。
strings.xmlの内容が下記のようになってると思います。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test01</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
これに「タイトル」「開始」「終了」を追加します。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test01</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title">string.xmlについて</string>
<string name="start">開始</string>
<string name="end">終了</string>
</resources>
次にactivity_main.xmlを編集して画面レイアウトを作成します
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test" />
</LinearLayout>
</LinearLayout>
画面イメージを確認すると、こんな感じになっていると思います。
次に画面内のコントロールとstrings.xmlを紐づけていきます
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title"
android:textSize="20sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
:text="@string/end"/>
画面イメージを確認すると、こんな感じになっていると思います。
ソース上で使用する場合は
String title = getString(R.string.title);
こうやって string.xml でテキスト情報を管理しておくと
多言語展開するとにも楽に対応できます。多言語化対応のソフトを作る日が来たらの話ですが・・
カテゴリーへ