이 튜토리얼에서는 안드로이드 앱에서 사용자가 EditText에 입력하는 동안 글자 수를 실시간으로 계산하여 화면에 표시하는 방법을 알아봅니다. TextWatcher 인터페이스를 활용하면 텍스트가 변경될 때마다 이벤트를 감지해 글자 수를 손쉽게 업데이트할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio를 실행한 후 File → New Project를 선택하고, 프로젝트 생성에 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에는 사용자 입력을 받을 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" android:padding="4dp" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ems="10" android:hint="EditText"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/editText" android:layout_marginBottom="20dp" android:layout_centerInParent="true" android:textSize="24sp" android:textStyle="bold" android:text="Count Display Here"/> </RelativeLayout>
3단계 — MainActivity.java 작성
src/MainActivity.java에 다음 코드를 추가합니다. 핵심은 addTextChangedListener() 메서드로 TextWatcher를 EditText에 등록하는 부분입니다.
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;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
int length = editText.length();
String convert = String.valueOf(length);
textView.setText(convert);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) { }
});
}
}TextWatcher의 주요 메서드 살펴보기
- beforeTextChanged() — 텍스트가 변경되기 직전에 호출됩니다. 이 예제에서는 이 메서드 안에서 현재 글자 수를 읽어와 TextView에 표시합니다.
- 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run 아이콘을 클릭하세요. 기기 목록에서 본인의 모바일 기기를 선택하면, 아래와 같이 EditText에 입력하는 대로 글자 수가 실시간으로 표시되는 것을 확인할 수 있습니다.


마무리
이처럼 TextWatcher만 활용하면 별도의 버튼 클릭 없이도 입력 즉시 글자 수를 화면에 반영할 수 있습니다. 이 방식은 회원가입 폼의 비밀번호 자릿수 안내, 게시글 작성 시 글자 수 제한 표시 등 다양한 UI에서 응용할 수 있으니 꼭 기억해 두세요.