AndroidでSearchViewを使ってRecyclerViewをフィルタリングする方法を解説
この記事では、AndroidアプリにおいてSearchViewを使用してRecyclerViewの表示内容をリアルタイムに絞り込む(フィルタリングする)方法を、実際のコード例とともに段階的に解説します。
全体の流れ
実装のポイントは以下の通りです。
- RecyclerViewに表示するデータリストを準備する
- アダプターに
Filterableインターフェースを実装する - メニューに配置したSearchViewの入力イベントを受け取り、フィルターを呼び出す
ステップ1:新規プロジェクトの作成
まず、Android Studioで新しいプロジェクトを作成します。「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>画面いっぱいにRecyclerViewを配置し、垂直方向のスクロールバーを有効にしています。
ステップ3:MainActivity.javaの実装
続いて、src/MainActivity.javaに以下のコードを記述します。
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;
}
}ここでの重要な処理はonCreateOptionsMenu()内です。setOnQueryTextListener()で検索テキストが変更されるたびにadapter.getFilter().filter(newText)を呼び出すことで、入力に応じてリアルタイムにリストが絞り込まれます。
ステップ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インターフェースを実装し、performFiltering()内で検索条件に一致する項目だけを抽出します。
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();
}
};
}ポイントは、コンストラクター内で元データのコピー(exampleListFull)を保持しておくことです。これにより、検索条件を空にした際に完全なリストへ復帰できます。また、toLowerCase().trim()で大文字・小文字や前後の空白を正規化しているため、より柔軟な検索が可能になっています。
ステップ6:リスト項目のレイアウト(example_item.xml)
各リスト項目の見た目を定義するため、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>CardViewで各項目をカード形式にし、画像・テキスト1行目・テキスト2行目を横並びで配置しています。
ステップ7:メニューリソース(example_menu.xml)
ツールバーに検索アイコンを表示するため、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>showAsAction="ifRoom|collapseActionView"を指定することで、スペースがあればアイコンとして表示され、タップするとSearchViewに展開されます。
ステップ8:マニフェスト(AndroidManifest.xml)
最後に、Manifest/AndroidManifest.xmlに以下のコードを記述します。
<?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>アプリの実行
それでは、実際にアプリを実行してみましょう。Android端末をパソコンに接続した状態で、Android Studioから任意のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択して実行すると、端末に以下のような初期画面が表示されます。

ツールバーの検索アイコンをタップして文字を入力すると、入力内容に一致する項目だけがRecyclerViewに表示され、テキストを削除すれば全項目が再び表示されます。これで、SearchViewによるRecyclerViewの動的フィルタリング機能の完成です。
-
【Android】RecyclerViewで無限スクロール(無限リスト)を実装する方法を徹底解説
はじめに 本記事では、AndroidアプリでRecyclerViewを使って無限リスト(エンドレススクロール)を実装する方法を、サンプルコード付きでステップごとに解説します。リストの最下部までスクロールすると自動的に次のデータが読み込まれるこの仕組みは、SNSやニュース系アプリなどで広く採用されている定番のUIパターンです。 今回実装する主な要素は以下のとおりです。 スクロール位置の検出による追加データ読み込みのトリガー処理 読み込み中に表示するプログレスバー(LoadingViewHolder) 複数のViewTypeを持つRecyclerView.Adapterの実装 手順1:プロジ
-
【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法を徹底解説
この記事では、AndroidアプリのTextViewでテキストを両端揃え(ジャスティファイ)表示する方法を、実際のサンプルコードをもとに段階的に解説します。RecyclerViewを使ったリスト表示の実装例もあわせて紹介するので、Androidアプリ開発の基礎固めとしても役立つ内容です。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な設定項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:res/layout/activity_main.xml