이 튜토리얼에서는 안드로이드 앱에서 커스텀 리스트뷰(ListView)에 검색 기능을 구현하는 방법을 단계별로 알아봅니다. 검색창(EditText)에 입력한 텍스트에 따라 리스트 항목이 실시간으로 필터링되도록 만들어 보겠습니다.
1단계: 새 프로젝트 생성
Android Studio를 열고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트를 생성하는 데 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성 (activity_main.xml)
다음 코드를 res/layout/activity_main.xml에 추가합니다. 화면 상단에는 검색어를 입력할 EditText, 하단에는 항목을 표시할 ListView가 배치됩니다.
<?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="8dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/etSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search here" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"
android:layout_below="@id/etSearch"/>
</RelativeLayout>3단계: 메인 액티비티 코드 작성 (MainActivity.java)
다음 코드를 src/MainActivity.java에 추가합니다. 여기서 핵심은 TextWatcher입니다. 검색창의 텍스트가 변경될 때마다 ArrayAdapter의 Filter를 호출하여 리스트가 자동으로 갱신됩니다.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> months = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
EditText etSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
etSearch = findViewById(R.id.etSearch);
months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, months);
listView.setAdapter(arrayAdapter);
etSearch.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) {
arrayAdapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}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(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

검색창에 텍스트를 입력하면 입력값과 일치하는 월(month) 항목만 리스트에 실시간으로 표시되는 것을 확인할 수 있습니다. 이처럼 TextWatcher와 ArrayAdapter의 Filter 기능을 조합하면 별도의 외부 라이브러리 없이도 간단하게 리스트뷰 검색 기능을 구현할 수 있습니다.