이번 튜토리얼에서는 안드로이드 앱에서 EditText에 텍스트를 입력하는 동안 조건에 맞는 이미지를 표시하는 방법을 단계별로 살펴봅니다. 핵심 아이디어는 TextWatcher로 입력 변화를 실시간으로 감지하고, 입력된 글자 수가 일정 개수(예제에서는 3자)를 넘으면 setCompoundDrawables() 메서드로 EditText 안에 Drawable 이미지를 보여주는 것입니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택한 뒤, 필요한 항목을 모두 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
아래 코드를 activity_main.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center"
android:layout_marginTop="30dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingStart="5dp"
android:background="@drawable/rounded_edittext"
android:drawableStart="@android:drawable/ic_menu_search"
android:paddingLeft="5dp" />
</LinearLayout>
위 코드는 세로 방향 LinearLayout 안에 EditText 하나를 배치하고, drawable 리소스인 rounded_edittext를 배경으로 지정했습니다. 자바 코드에서 해당 뷰를 참조할 수 있도록 android:id="@+id/edit_query" 속성도 함께 추가했습니다.
3단계 — 배경 드로어블 작성 (drawable/rounded_edittext.xml)
res/drawable 폴더에 rounded_edittext.xml 파일을 만들고 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#2f6699" />
<corners
android:radius="10dp" />
</shape>
이 셰이프는 흰색(#FFFFFF) 배경에 두께 1dp의 파란색(#2f6699) 테두리와 10dp의 둥근 모서리를 적용해 부드러운 검색창 느낌을 줍니다.
4단계 — MainActivity 작성 (java/MainActivity.java)
메인 액티비티에 아래 코드를 작성합니다. 패키지 이름(com.example.myapplication)은 실제 프로젝트 환경에 맞게 수정하고, drawable 폴더에 sir.png와 같은 표시용 이미지 리소스가 미리 준비되어 있어야 합니다.
package com.example.myapplication;
import android.annotation.TargetApi;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edit_query);
final Drawable image = MainActivity.this.getResources().getDrawable(R.drawable.sir);
image.setBounds(0, 0, 40, 40);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
editText.setCompoundDrawables(null, null, null, null);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count > 2 && count != 0)
editText.setCompoundDrawables(image, null, null, null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
코드 설명:
getResources().getDrawable()로 표시할 이미지를 가져오고,setBounds(0, 0, 40, 40)으로 크기를 40×40으로 지정합니다.addTextChangedListener()로 TextWatcher를 등록해 사용자의 입력 변화를 감지합니다.onTextChanged()에서 새로 입력된 글자 수(count)가 3보다 크면setCompoundDrawables(image, null, null, null)를 호출해 EditText 왼쪽에 이미지를 표시합니다.beforeTextChanged()에서는 모든 Drawable을 null로 설정해 조건에 맞지 않을 때 이미지를 다시 숨깁니다.
5단계 — 실행 및 결과 확인
앱을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결한 상태에서 Android Studio 툴바의 Run 아이콘을 클릭하고, 목록에서 본인의 기기를 선택하세요. 그러면 아래와 같은 기본 화면이 표시됩니다.

이제 3글자 이상 입력하면 다음 화면처럼 EditText에 이미지가 함께 나타나는 것을 확인할 수 있습니다.
