Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 커스텀 리스트뷰(ListView) 검색 기능 구현하기

안드로이드 앱에서 많은 양의 데이터를 목록 형태로 보여줘야 할 때 ListView는 가장 널리 쓰이는 위젯 중 하나입니다. 이 글에서는 Kotlin을 사용해 커스텀 리스트뷰에 실시간 검색 기능을 구현하는 방법을 단계별로 소개합니다. 검색창에 입력한 텍스트에 따라 목록 항목이 자동으로 걸러지는 기능으로, 코드량이 적어 초보자도 쉽게 따라 할 수 있습니다.

1단계: 새 프로젝트 만들기

Android Studio에서 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 정보를 모두 입력합니다. 개발 언어는 반드시 Kotlin으로 선택하세요.

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="4dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search here" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/etSearch" />
</RelativeLayout>

3단계: MainActivity.kt 구현

src/MainActivity.kt 파일에 다음 코드를 작성합니다. 1월부터 12월까지 월 이름을 ArrayList에 담아 ArrayAdapter로 ListView에 연결한 뒤, EditText에 TextWatcher를 등록하는 것이 이 예제의 핵심입니다.

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 androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var listView: ListView
    var months: ArrayList<String> = ArrayList()
    var arrayAdapter: ArrayAdapter<String>? = null
    lateinit var etSearch: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        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 = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, months)
        listView.adapter = arrayAdapter
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                arrayAdapter!!.filter.filter(s)
            }
            override fun afterTextChanged(s: Editable) {}
        })
    }
}

동작 원리: TextWatcher의 세 가지 콜백 중 onTextChanged()는 입력 텍스트가 바뀌는 순간마다 호출됩니다. 여기서 arrayAdapter!!.filter.filter(s)를 실행하면 ArrayAdapter에 내장된 필터 기능이 동작해, 입력된 문자열을 포함하는 항목만 목록에 남습니다. 기본 필터는 대소문자를 구분하지 않으므로 별도의 처리 없이도 자연스러운 검색 환경을 제공합니다.

4단계: AndroidManifest.xml 설정

androidManifest.xml은 아래와 같습니다. 인터넷 권한 등 별도의 권한 선언은 필요 없으며, MainActivity가 런처(LAUNCHER) 액티비티로 올바르게 등록되어 있는지만 확인하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <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 아이콘을 클릭하고, 옵션 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 앱의 기본 화면이 표시됩니다.

Kotlin으로 안드로이드 커스텀 리스트뷰(ListView) 검색 기능 구현하기

Kotlin으로 안드로이드 커스텀 리스트뷰(ListView) 검색 기능 구현하기

검색창에 예를 들어 'J'를 입력하면 January, June, July 세 항목만 목록에 남습니다. 이처럼 TextWatcher와 ArrayAdapter의 filter()만 활용하면 몇 줄의 코드로 리스트뷰에 강력한 검색 기능을 손쉽게 추가할 수 있습니다.