개요
이 튜토리얼에서는 안드로이드 앱에서 SearchView를 사용해 RecyclerView의 항목을 실시간으로 검색하고 필터링하는 방법을 단계별로 살펴봅니다. 사용자가 검색창에 입력하는 즉시 어댑터의 Filter 기능이 동작하여, 조건에 맞는 항목만 목록에 표시되도록 구현합니다.
1단계 — 새 프로젝트 생성
안드로이드 스튜디오에서 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — activity_main.xml 작성
res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" android:scrollbars="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
3단계 — MainActivity.java 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다. 여기서 메뉴에 포함된 SearchView에 OnQueryTextListener를 등록해, 검색어가 변경될 때마다 어댑터의 필터를 호출하는 것이 핵심입니다.
package com.app.sample;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.SearchView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExampleAdapter adapter;
private List<ExampleItem> exampleList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillExampleList();
setUpRecyclerView();
}
private void fillExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new ExampleItem(R.drawable.ic_android, "One", "Ten"));
exampleList.add(new ExampleItem(R.drawable.ic_audio, "Two", "Eleven"));
exampleList.add(new ExampleItem(R.drawable.ic_sun, "Three", "Twelve"));
exampleList.add(new ExampleItem(R.drawable.ic_android, "Four", "Thirteen"));
exampleList.add(new ExampleItem(R.drawable.ic_audio, "Five", "Fourteen"));
exampleList.add(new ExampleItem(R.drawable.ic_sun, "Six", "Fifteen"));
exampleList.add(new ExampleItem(R.drawable.ic_android, "Seven", "Sixteen"));
exampleList.add(new ExampleItem(R.drawable.ic_audio, "Eight", "Seventeen"));
exampleList.add(new ExampleItem(R.drawable.ic_sun, "Nine", "Eighteen"));
}
private void setUpRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
adapter = new ExampleAdapter(exampleList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
4단계 — ExampleItem.java 작성
목록에 표시할 데이터를 담는 모델 클래스입니다. src/ExampleItem.java 파일에 다음 코드를 추가합니다.
package com.app.sample;
public class ExampleItem {
private int imageResource;
private String text1;
private String text2;
public ExampleItem(int imageResource, String text1, String text2) {
this.imageResource = imageResource;
this.text1 = text1;
this.text2 = text2;
}
public int getImageResource() {
return imageResource;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
}
5단계 — ExampleAdapter.java 작성
필터링의 핵심인 어댑터입니다. Filterable 인터페이스를 구현하고, 전체 목록(exampleListFull)을 별도로 보관한 뒤 검색 조건에 맞는 항목만 추려 화면에 반영합니다. performFiltering()은 백그라운드 스레드에서 실행되므로 대량의 데이터를 필터링할 때도 UI가 멈추지 않습니다.
package com.app.sample;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ExampleAdapter extends
RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> implements Filterable {
private List<ExampleItem> exampleList;
private List<ExampleItem> exampleListFull;
class ExampleViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView1;
TextView textView2;
ExampleViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
textView1 = itemView.findViewById(R.id.text_view1);
textView2 = itemView.findViewById(R.id.text_view2);
}
}
ExampleAdapter(List<ExampleItem> exampleList) {
this.exampleList = exampleList;
exampleListFull = new ArrayList<>(exampleList);
}
@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = exampleList.get(position);
holder.imageView.setImageResource(currentItem.getImageResource());
holder.textView1.setText(currentItem.getText1());
holder.textView2.setText(currentItem.getText2());
}
@Override
public int getItemCount() {
return exampleList.size();
}
@Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<ExampleItem> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(exampleListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (ExampleItem item : exampleListFull) {
if (item.getText2().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
exampleList.clear();
exampleList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
6단계 — example_item.xml 작성
RecyclerView의 각 항목 레이아웃입니다. 카드 형태로 이미지와 두 줄의 텍스트를 배치합니다. res/layout/example_item.xml 파일에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="4dp" app:cardCornerRadius="4dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="4dp"> <ImageView android:id="@+id/image_view" android:layout_width="50dp" android:layout_height="50dp" android:padding="2dp" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toEndOf="@+id/image_view" android:text="Line 1" android:textColor="@android:color/black" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/text_view1" android:layout_marginStart="8dp" android:layout_toEndOf="@+id/image_view" android:text="Line 2" android:textSize="15sp" /> </RelativeLayout> </android.support.v7.widget.CardView>
7단계 — example_menu.xml 작성
앱 바(App Bar)에 검색 메뉴 항목을 추가합니다. res/menu/example_menu.xml 파일에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <item android:id="@+id/actionSearch" android:title="Search" app:showAsAction="ifRoom|collapseActionView" /> </menu>
8단계 — AndroidManifest.xml 확인
Manifest/AndroidManifest.xml 파일이 아래와 같이 MainActivity를 런처 액티비티로 등록하고 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.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>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 기기로 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

마무리
이 예제의 핵심 흐름을 정리하면 다음과 같습니다.
① SearchView의 onQueryTextChange()에서 입력값이 변경될 때마다 어댑터의 getFilter().filter()를 호출 → ② performFiltering()에서 전체 목록을 대상으로 검색어와 일치하는 항목만 추출 → ③ publishResults()에서 필터링된 목록으로 교체하고 notifyDataSetChanged()로 화면을 갱신합니다.
검색 대상 필드를 바꾸고 싶다면 performFiltering() 내부의 getText2()를 원하는 필드로 수정하면 되고, 대소문자 구분 없이 검색하려면 비교 전에 toLowerCase() 처리를 유지하면 됩니다. 이 패턴을 응용하면 다중 조건 검색이나 정렬 기능도 손쉽게 확장할 수 있습니다.