Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 TextWatcher 클래스 사용법 – EditText 입력 실시간 감지하기

이 튜토리얼에서는 안드로이드 앱에서 TextWatcher 클래스를 사용하는 방법을 단계별 예제와 함께 살펴봅니다.

TextWatcher란 무엇인가?

TextWatcher는 EditText와 같은 텍스트 입력 위젯의 내용이 변경될 때마다 이벤트를 감지할 수 있도록 해주는 인터페이스입니다. 구현해야 하는 콜백 메서드는 다음 세 가지입니다.

  • beforeTextChanged() – 텍스트가 변경되기 직전에 호출됩니다.
  • onTextChanged() – 텍스트가 변경되는 순간 호출됩니다.
  • afterTextChanged() – 텍스트 변경이 완료된 후 호출됩니다.

이번 예제에서는 EditText에 입력된 텍스트를 실시간으로 TextView에 출력하고, 최대 글자 수 제한에 도달하면 토스트 메시지를 표시하는 기능을 구현해 보겠습니다.

구현 단계

1단계 – 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계 – 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?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>

여기서 EditText에는 android:maxLength="15" 속성으로 최대 15글자까지 입력 가능하도록 설정했습니다.

3단계 – MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

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) {
        }
    };
}

핵심은 addTextChangedListener() 메서드로 TextWatcher 객체를 EditText에 등록하는 부분입니다. 이후 입력값이 바뀔 때마다 onTextChanged()가 호출되어 TextView에 텍스트가 그대로 반영되고, 입력 위치(start)가 12에 도달하면 "Maximum Limit Reached" 토스트가 표시됩니다.

참고: 최신 Android Studio 프로젝트에서는 지원 라이브러리 대신 AndroidX를 사용하므로, import 문을 androidx.appcompat.app.AppCompatActivity로 변경하면 됩니다.

4단계 – 매니페스트 설정

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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.


안드로이드 TextWatcher 클래스 사용법 – EditText 입력 실시간 감지하기

안드로이드 TextWatcher 클래스 사용법 – EditText 입력 실시간 감지하기

마무리

이처럼 TextWatcher를 활용하면 사용자가 입력하는 텍스트를 실시간으로 감지할 수 있습니다. 검색창 자동완성, 글자 수 제한 알림, 입력값 유효성 검사 등 다양한 기능을 손쉽게 구현할 수 있으니, 실제 프로젝트에 적극적으로 응용해 보시기 바랍니다.