XMLファイルから文字列リソースを参照

広告

文字列リソースをプログラムからではなくレイアウト用XMLファイルなどから参照することも可能です。XMLファイル内から文字列リソースを参照する場合には次のように記述します。

@string/ID

「ID」には文字列リソースに対して「R.java」ファイル内で割り当てられた値を指定します。

それでは実際に試してみます。まずテスト用に「test04_01」と言うプロジェクトを作成します。

XMLファイルから文字列リソースを参照

次に文字列リソースを定義するためのXMLファイルを作成します。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello_msg">Hello Android</string>
    <string name="hello_msg_jp">こんにちは</string>
</resources>

上記を「str.xml」と言うファイル名で保存して下さい。保存する場所はプロジェクト内の「res/values」ディレクトリの中です。文字コードを「UTF-8」にするのを忘れないで下さい。

XMLファイルから文字列リソースを参照

ではこの時点で一度ビルドして下さい。「R.java」が作成されます。中身は次のようになっているはずです。

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package jp.javadrive.android;

public final class R {
    public static final class attr {
    }
    public static final class layout {
        public static final int main=0x7f020000;
    }
    public static final class string {
        public static final int app_name=0x7f030002;
        public static final int hello_msg=0x7f030000;
        public static final int hello_msg_jp=0x7f030001;
    }
}

XMLファイルから2つの文字列リソースを参照するには「@string/hello_msg」と「@string/hello_msg_jp」と記述します。

レイアウト用XMLファイルの作成

次にレイアウト用XMLファイルを作成します。今回はデフォルトで用意されている「main.xml」ファイルの中身を書き換えます。(もし作成されていなければ「main.xml」と言うファイルを新規に作成して下さい)。XMLファイルの位置はプロジェクト内の「res/layout」ディレクトリの中に含まれています。

XMLファイルから文字列リソースを参照

XMLファイルの内容を次のように書き換えます。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:text="@string/hello_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />

    <Button
        android:text="@string/hello_msg_jp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />

</LinearLayout>

今回は2つのボタンを用意し、それぞれのボタンの表示テキストとして外部に用意した文字列リソースを設定しています。設定する場合の注意点としてダブルクオーテーションで囲って設定する点に注意して下さい。

プログラムの変更

最後にデフォルトで作成されている「Test04_01.java」をテキストエディタで開き次のように修正します。

Test04_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;

public class Test04_01 extends Activity
{
    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    }
}

今回はXMLファイルとして用意したレイアウトを読み込んでいるだけです。

以上で準備が完了しました。では改めてビルドを行いエミュレーターにアプリケーションをインストールして下さい。その後アプリケーションを起動すると次のように表示されます。

XMLファイルから文字列リソースを参照

このようにリソースとして登録した文字列をレイアウト用のXMLファイルの中で参照することが出来ました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。