AndroidでTextWatcherクラスを使う方法をステップごとに解説
この記事では、Androidアプリ開発においてTextWatcherクラスを使用する方法を、実際のコード例とともに詳しく解説します。TextWatcherは、EditTextなどに入力されたテキストの変化をリアルタイムに監視できる便利なインターフェースです。入力内容の即時反映や文字数制限のチェックなど、さまざまな場面で活用できます。
完成するサンプルアプリについて
今回作成するのは、EditTextに入力したテキストがそのままTextViewに表示されるシンプルなアプリです。さらに、最大文字数(15文字)に達すると「Maximum Limit Reached」というトーストメッセージを表示します。
手順1:新しいプロジェクトを作成する
Android Studioを開き、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力し、プロジェクトのセットアップを完了させてください。
手順2:レイアウトファイル(activity_main.xml)を作成する
res/layout/activity_main.xml に以下のコードを追加します。タイトル用のTextView、テキスト入力用のEditText、入力結果を表示するTextViewを配置しています。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Text Watcher"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginTop="24sp"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/text"
android:maxLength="15"
android:hint="Input" />
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:layout_below="@id/etInput"/>
</RelativeLayout>手順3:MainActivity.javaにTextWatcherを実装する
src/MainActivity.java に以下のコードを記述します。addTextChangedListener()メソッドでTextWatcherを登録し、onTextChanged()内で入力内容をTextViewへ反映しています。また、入力位置が12文字目に達したときにトーストで上限を通知します。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText input;
TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = findViewById(R.id.etInput);
output = findViewById(R.id.textView);
input.addTextChangedListener(textWatcher);
}
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
output.setText(s);
if (start == 12){
Toast.makeText(getApplicationContext(), "Maximum Limit Reached", Toast.LENGTH_SHORT).show();
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
}TextWatcherの3つのコールバックメソッド
- beforeTextChanged():テキストが変更される直前に呼ばれます。
- onTextChanged():テキストが変更されたときに呼ばれます。ここでリアルタイム処理を行います。
- afterTextChanged():テキストの変更が完了した後に呼ばれます。
手順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スマートフォンをPCに接続していることを前提とします。Android Studioから実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの実行アイコンをクリックします。デバイス一覧から自分のスマートフォンを選択すると、端末上に以下のような画面が表示されます。


EditTextに入力すると、その内容が下のTextViewに即座に反映されることが確認できます。これで、AndroidにおけるTextWatcherクラスの基本的な使い方をマスターできました。検索ボックスの絞り込み表示やフォームのバリデーションなど、応用範囲は非常に広いので、ぜひ実際のプロジェクトでも活用してみてください。
-
AndroidのツールバーでSearchViewを実装する方法【ステップ解説】
はじめに 本記事では、Androidアプリのツールバー(Toolbar)にSearchViewを組み込み、リストの絞り込み検索機能を実装する方法を、ステップバイステップで解説します。サンプルとして月名の一覧をListViewに表示し、SearchViewに入力したキーワードでリアルタイムに検索結果をフィルタリングする仕組みを作ります。 手順1:新規プロジェクトの作成 まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイルの編集 次に、res/lay
-
AndroidアプリでCalendarViewクラスを使ってカレンダーウィジェットを実装する方法
このチュートリアルでは、AndroidアプリでCalendarViewクラスを使用してカレンダーウィジェットを実装し、ユーザーが選択した日付を取得して表示する方法を解説します。カレンダーウィジェットを使えば、日付の選択UIを簡単に組み込むことができます。ステップ1:新しいプロジェクトを作成するAndroid Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。ステップ2:レイアウトファイル(activity_main.xml)を編集するres/layout/activity_mai