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

【Android開発】EditTextフィールドの値を取得する方法をサンプルコード付きで解説

この記事では、Androidアプリ開発においてEditText(テキスト入力フィールド)に入力された値を取得して画面に表示する方法を、実際のサンプルコードを使いながらステップごとにわかりやすく解説します。

作成するアプリの概要

今回作成するのは、EditTextに入力した文字列をボタンをタップしたタイミングで取得し、TextViewに表示するシンプルなアプリです。入力値の取得には getText().toString() メソッドを使用します。手順は以下の4ステップです。

  1. Android Studioで新規プロジェクトを作成する
  2. レイアウトXML(activity_main.xml)を作成する
  3. MainActivity.javaに入力値の取得処理を記述する
  4. AndroidManifest.xmlを確認する

ステップ1:Android Studioで新規プロジェクトを作成

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

ステップ2:レイアウトファイル(res/layout/activity_main.xml)

次に、res/layout/activity_main.xml に以下のコードを追加します。EditText・Button・TextViewの3つのビューを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/button"
        android:layout_centerInParent="true"/>

    <Button
        android:id="@+id/button"
        android:text="値を取得"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/textView"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_centerInParent="true"
        android:layout_below="@id/button"
        android:layout_marginTop="8dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

ステップ3:MainActivity.javaに入力値の取得処理を記述

src/MainActivity.java に以下のコードを追加します。最重要ポイントは、ボタンクリック時の処理内にある editText.getText().toString() の部分です。この1行でEditTextに入力された文字列をString型として取得できます。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button button;
    EditText editText;
    String string;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // EditTextの入力値を取得してTextViewに表示
                string = editText.getText().toString();
                textView.setText(string);
            }
        });
    }
}

※近年のAndroid StudioではAndroidXが標準のため、新しいプロジェクトでは import文を androidx.appcompat.app.AppCompatActivity に読み替えてください。

ステップ4: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」アイコンをクリックします。デバイス選択ダイアログで接続した端末を選択すると、スマートフォンにアプリの初期画面が表示されます。

EditTextに任意の文字列を入力して「値を取得」ボタンをタップすると、入力した内容が下のTextViewに表示されます。

【Android開発】EditTextフィールドの値を取得する方法をサンプルコード付きで解説

まとめ

EditTextの入力値を取得する基本は getText().toString() です。ボタンのクリックリスナー内で呼び出せば、ユーザーが入力した最新の値をいつでも取り出せます。検索機能やフォーム入力など、あらゆるアプリで使われる基礎技術なので、ぜひマスターしておきましょう。

  1. TkinterのEntryウィジェットから値を取得する方法【.get()メソッドの使い方】

    Tkinterでアプリケーションを開発していると、作成したEntryウィジェット(テキスト入力欄)に入力された値を取得したい場面が出てきます。そんなときに活用できるのが.get()メソッドです。このメソッドを使うと、ユーザーが入力した内容を変数として受け取ることができ、その値を画面に表示したり、他の処理に利用したりできます。 実装例:入力したテキストをラベルに表示する ここでは、Entryウィジェットに入力されたテキストを取得し、Labelウィジェットを使って画面に表示する簡単なアプリケーションを作成してみましょう。 # tkinterライブラリをインポート from tkinter impo

  2. Redis HSTRLENコマンドの使い方 – ハッシュ内フィールド値の文字数を取得する方法

    このチュートリアルでは、Redisデータストア上のキーに保存されたハッシュ値に含まれる、特定フィールドの値の長さ(文字数)を取得する方法を解説します。この目的には、RedisのHSTRLENコマンドを使用します。 HSTRLENコマンドとは HSTRLENコマンドは、指定したキーに保存されているハッシュ値の中から、対象となるフィールドに関連付けられた値の長さ(文字数)を返します。動作のポイントは以下の通りです。 キーが存在しない場合 → 0 が返される キーは存在するが、ハッシュ値に指定したフィールドが含まれていない場合 → 0 が返される キーは存在するが、保存されている値がハッシュ型では