Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidのカスタムListViewに検索機能を実装する方法【サンプルコード付き】

はじめに

このチュートリアルでは、Androidアプリの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 です。addTextChangedListener() でEditTextへの入力を監視し、onTextChanged() 内で ArrayAdapter の getFilter().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スマートフォンがパソコンに接続されているものとします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択すると、端末に以下のような初期画面が表示されます。

AndroidのカスタムListViewに検索機能を実装する方法【サンプルコード付き】

検索ボックスに「J」などと入力すると、「January」「June」「July」のように該当する項目だけがリストに表示されます。これで、EditTextとTextWatcherを組み合わせた簡単な検索機能が正しく動作していることを確認できます。

  1. 【Android】カスタムAlertDialogビューを実装する完全ガイド

    この記事では、AndroidアプリでカスタムAlertDialog(ダイアログ)を実装する方法を、サンプルコード付きで段階的に解説します。標準的なダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。 ステップ1:新規プロジェクトの作成 まず、Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。 ステップ2:activity_main.xml にコードを追加 res/layout/activity_main.xml に以下のコードを記

  2. Androidでカスタムジェスチャーを追加して操作を時短する方法

    Androidデバイスにカスタムジェスチャーを設定すれば、日々のスマホ操作をぐっと快適にできます。自分が一番使いやすい動きで、新しいタブを開くなどの特定のタスクを実行できるように、端末を自由にカスタマイズできるのが魅力です。 例えば、画面の上端からスワイプするだけで最近使ったアプリへアクセスできたら便利だと思いませんか?カスタムジェスチャーがない状態では、クイック設定パネル( Wi-Fiや歯車アイコンなど)にしかアクセスできません。この記事では、代表的なカスタムジェスチャーアプリを紹介しながら、設定方法をわかりやすく解説します。 All in One Gesturesでカスタムジェスチャーを追