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

【Android入門】strings.xmlから値を読み取る方法を初心者向けに解説

はじめに

このチュートリアルでは、Androidアプリでstrings.xml(文字列リソースファイル)に定義した値を読み取り、画面に表示する方法を段階的に解説します。文字列をリソースファイルで一元管理することで、多言語対応や保守性の向上にもつながるため、Android開発における基本的なテクニックの一つです。

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。プロジェクト名やパッケージ名、保存先などの必要な項目を入力して、新しいプロジェクトを作成しましょう。

ステップ2:strings.xmlに文字列を定義する

res/values/strings.xmlに以下のコードを追加します。

<resources>
    <string name="app_name">Sample</string>
    <string name="NameOfTheString">Test string</string>
</resources>

ここでは、「NameOfTheString」という名前で「Test string」という文字列を定義しています。この名前をキーにして、後ほど文字列を参照します。

ステップ3:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを記述します。TextViewのandroid:text属性に「@string/NameOfTheString」を指定することで、strings.xmlで定義した文字列を直接参照できます。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:text="@string/NameOfTheString"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

ステップ4:MainActivity.javaを編集する

src/MainActivity.javaに以下のコードを記述します。今回はレイアウト側で文字列を直接参照しているため、Activity側は標準的な実装だけで動作します。

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

ステップ5:AndroidManifest.xmlを確認する

app/manifests/AndroidManifest.xmlに以下のコードを記述します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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」アイコンをクリックします。表示された候補から接続済みのモバイルデバイスを選択すると、端末の画面に以下のように定義した文字列が表示されます。

【Android入門】strings.xmlから値を読み取る方法を初心者向けに解説

補足:コードから文字列リソースを取得する方法

Javaコード内でstrings.xmlの値を取得したい場合は、getString()メソッドを使用します。

String value = getString(R.string.NameOfTheString);

Kotlinの場合は以下のように記述できます。

val value = getString(R.string.NameOfTheString)

このように、XMLレイアウトでは「@string/リソース名」、コード上では「R.string.リソース名」を使い分けることで、どこからでも文字列リソースを参照できます。

  1. Androidからマルウェアを削除する方法|感染の兆候と予防策を徹底解説

    現代社会において、スマートフォンは生活に欠かせない存在となっています。銀行アプリ、ナビゲーションアプリ、各種ユーティリティアプリなど、個人の重要な情報や機能がほぼすべて詰まっています。だからこそ、プライバシーを守るためにも、スマートフォンをしっかりと保護することが何よりも重要です。パソコンと同様に、Androidスマートフォンもウイルス、トロイの木馬、スパイウェア、アドウェアなどの悪意あるプログラム(マルウェア)に感染する可能性があります。Androidマルウェアの主な目的は、機密情報の窃取、無関係な広告の表示によるユーザーの誤誘導、悪質なサイトへのリダイレクトなどです。マルウェアはさまざまな

  2. C#で文字列からXDocumentにXMLデータを読み込む方法

    XMLは自己記述型の言語であり、データそのものに加えて、その情報が何を意味するのかを識別するためのルールも併せて提供します。HTMLと同様に、XMLはSGML(Standard Generalized Markup Language:標準汎用マークアップ言語)のサブセットです。 XDocumentクラスには、有効なXMLドキュメントとして成立させるために必要な情報が格納されます。具体的には、XML宣言、処理命令、コメントなどが含まれます。 XDocumentを使うべきケースとは? 注意すべき点として、XDocumentクラスが提供する特定の機能が必要な場合にのみXDocumentオブジェクトを