메뉴 건너뛰기

조회 수 557 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

안드로이드 앱에서 사용자로부터 값을 입력받을 때 사용되는 View 위젯 중 EditText가 있습니다. 앱을 구현하다 보면 이러한 EditText의 Text 입력값이 변경될 때마다 특정 작업을 처리해야 할 경우가 있습니다. 

이때는 TextWatcher 인터페이스를 구현하여 EditText의 이벤트 리스너로 등록하여 처리가 가능합니다.

 

 

 


 

1. TextWatcher 인터페이스 필구 구현 함수들

■ beforeTextChanged(CharSequence s. int start, int count, int after)

  • CharSequece s : 현재 EditText에 입력된 값

  • int start : s에 저장된 문자열에서 새로 추가될 문자열의 시작 위치 값

  • int count : s에 새로운 문자열이 추가된 후 문자열의 길이

  • int after : 새로 추가될 문자열의 길이

■ onTextChanger(CharSequence s, int start, int before, int count)

 

start 위치에서 before 문자열 개수만큼 문자열이 count 개수만큼 변경되었을 때 호출

  • CharSequence s : 새로 입력한 문자열이 추가된 EditText의 값을 가지고 있음

  • int start : 새로 추가된 문자열의 시작 위치 값

  • int before : 삭제된 기존 문자열의 개수

  • int count : 새로 추가된 문자열의 개수 

■ afterTextChanged(Editalbe a)

 

EditText의 Text가 변경된 것을 다른 곳에 통보할 때 사용됩니다. a.toString()을 통해 현재 EditText의 Text 값을 불러오는 게 가능합니다. EditText의 Text 변경에 따른 함수 호출 순서는  beforeTextChanged,  onTextChanger,  afterTextChanged 순으로 호출됩니다.

 

 

 


2. TextWatcher 구현 예제

먼저 Main 화면의 Xml 레이아웃 리소스입니다. 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text=""
        android:textSize="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText" />
</android.support.constraint.ConstraintLayout>

▼ EditText 하나와 TextView 하나를 배치한 형태입니다. TextWatcher 구현체를 등록한 EdiText의 값이 변경될 때마다 TextView의 Text에 반영되도록 구현할 것입니다.

package com.springsthursday.textwatcher;

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 {
    private EditText editText;
    private TextView textView;

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

        this.getViewObject();

        editText.addTextChangedListener(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) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                textView.setText(s.toString());
            }
        });
    }

    private void getViewObject()
    {
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
    }
}

 

 

 

▼ getViewObject() 함수에서 레이아웃 리소스 상의 TextView와 EditText의 참조 객체를 얻어옵니다. onCreate() 함수에서는 EditText의 addTextChangedListener() 함수를 통해 Text 값 변경에 따른 이벤트 리스너를 등록해주는데 익명 클래스 작성법을 통하여 TextWatcher() 인터페이스를 구현한 객체를 전달합니다.

 

 

 

 


List of Articles
번호 제목 날짜 조회 수
157 안드로이드 - 색상 리소스 (Color Resource) 추가 </color> file 2021.03.31 551
156 안드로이드 - 뷰페이저(ViewPager) 구현 file 2021.04.02 323
155 안드로이드 - 버튼 이벤트 처리방법 정리 (리스너 구현 및 이벤트 핸들링) file 2021.03.31 343
154 안드로이드 - 문자열 배열 리소스 추가하기 <string-array> file 2021.03.31 811
153 안드로이드 - 문자열 리소스를 활용한 다국어 지원 file 2021.03.31 282
152 안드로이드 - 문자열 리소스(Resource) 추가 및 참조하기 file 2021.03.31 906
151 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
150 안드로이드 - 리스트뷰(ListView) 구현 file 2021.04.01 490
149 안드로이드 - 리사이클러뷰 (RecyclerView) notifyDataSetChanged 실행 시 깜빡 거리는 현상 2021.04.02 746
148 안드로이드 - 리사이클러 뷰(RecyclerView) 구현 file 2021.04.01 388
147 안드로이드 - 리니어 레이아웃 (Linear Layout) file 2021.03.29 319
146 안드로이드 - 랠러티브 레이아웃(Relative Layout) file 2021.03.29 239
145 안드로이드 - 네비게이션 드로어(Navigation Drawer)를 활용하여 슬라이드 메뉴 구현하기 file 2021.04.01 1858
144 안드로이드 - 날짜 및 시간 정보 입력받기 (DatePickerDialog / TimePickerDialog) file 2021.04.01 1762
143 안드로이드 - 갤러리에서 이미지 가져오기 2021.04.02 666
» 안드로이드 - Text 입력 이벤트 처리 - TextWatcher file 2021.04.02 557
141 안드로이드 - switch를 사용법 및 구현 file 2021.04.02 1280
140 안드로이드 - SQLiteDatabase 구현하기 file 2021.04.01 243
139 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 282
138 안드로이드 - SharedPreferences에 앱 정보 저장하기 file 2021.04.02 395
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved