본문 바로가기
안드로이드 자바

[Java][Android] 리사이클러뷰 검색 필터링 구현하기

by teamnova 2021. 3. 20.

이번 시간에는 리사이클러뷰에 검색(필터 된) 아이템을 보여주는 기능을 구현해보겠습니다.

제가 예제로 하려는 것은 음식을 검색했을 때 그 단어가 포함된 음식을 보여주도록 하는 것입니다.

(예를 들면 닭을 검색했을 때 닭볶음탕 , 닭가슴살 등 이런 식..!)

 

먼저 리사이클러뷰를 사용해야 하기 때문에  build.gradle 파일의 의존성 설정에 추가합니다.

 



implementation 'androidx.recyclerview:recyclerview:1.1.0'
    
    

 

 

그다음 아이템 클래스와 아이템 레이아웃을 만들어 보겠습니다.!

리사이클러뷰에서는 음식 이름만 보여줄 것입니다.

그렇기 때문에 아이템클래스에서는 음식 이름만 있고 , 아이템 레이아웃에서는 텍스트뷰만 있습니다~

 

FoodItem.java

 

package com.example.stickode4;

public class FoodItem {

    String foodName;

    public FoodItem(String foodName) {
        this.foodName = foodName;
    }

    public String getFoodName() {
        return foodName;
    }

    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

}

 

 

item_food.xml

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/foodName"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="#111111"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

그다음에 어댑터를 만들어주겠습니다.

다른것과 다른 점은 filterList 메서드가 있다는 점입니다.

filterList 메서드는 검색할때 해당 검색어가 포함되면 그 목록을 보여줍니다.

 

FoodAdapter.java

 

package com.example.stickode4;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder>{


    ArrayList<FoodItem> foodItemArrayList;
    Activity activity;


    public FoodAdapter(ArrayList<FoodItem> foodItemArrayList, Activity activity) {
        this.foodItemArrayList = foodItemArrayList;
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_food,null);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

        holder.foodName.setText(foodItemArrayList.get(position).getFoodName());

    }

    @Override
    public int getItemCount() {
        return foodItemArrayList.size();
    }

    public void  filterList(ArrayList<FoodItem> filteredList) {
        foodItemArrayList = filteredList;
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        TextView foodName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            this.foodName=itemView.findViewById(R.id.foodName);

        }
    }
}

 

그다음에 메인 레이아웃과 액티비티를 만들어보겠습니다.

메인 레이아웃에서는 먹고싶은 음식을 검색하는 EditText와 음식 목록을 보여줄 리사이클러뷰가 있습니다.

(검색 버튼이라던가 , 검색을 했을 때 보여지는것들 구현하지 않았습니다. 원하신다면 따로 원하시는 부분에 작성하시면 될 것 같습니다.)

 

activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:background="#f5f5f5"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <EditText
        android:id="@+id/searchFood"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="먹고싶은 음식 검색"
        android:layout_marginTop="10sp"
        android:layout_marginHorizontal="10sp"
        android:lines="1"
        app:layout_constraintBottom_toTopOf="@id/recyclerview"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#f5f5f5"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/searchFood"
        tools:listitem="@layout/item_food"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

MainActivity.java

 

package com.example.stickode4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<FoodItem> foodItemArrayList, filteredList;
    FoodAdapter foodAdapter;
    RecyclerView recyclerView;
    LinearLayoutManager linearLayoutManager;
    EditText searchET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerview);
        searchET = findViewById(R.id.searchFood);

        filteredList=new ArrayList<>();
        foodItemArrayList = new ArrayList<>();

        foodAdapter = new FoodAdapter(foodItemArrayList, this);
        linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(foodAdapter);

        foodItemArrayList.add(new FoodItem("닭가슴살"));
        foodItemArrayList.add(new FoodItem("피자"));
        foodItemArrayList.add(new FoodItem("햄버"));
        foodItemArrayList.add(new FoodItem("제육볶음"));
        foodItemArrayList.add(new FoodItem("닭갈비"));
        foodItemArrayList.add(new FoodItem("바지락 칼국수"));
        foodItemArrayList.add(new FoodItem("닭볶음탕"));
        foodAdapter.notifyDataSetChanged();


        searchET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                String searchText = searchET.getText().toString();
                searchFilter(searchText);

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void searchFilter(String searchText) {
        filteredList.clear();

        for (int i = 0; i < foodItemArrayList.size(); i++) {
            if (foodItemArrayList.get(i).getFoodName().toLowerCase().contains(searchText.toLowerCase())) {
                filteredList.add(foodItemArrayList.get(i));
            }
        }

        foodAdapter.filterList(filteredList);
    }

}

 

 

빠르게 구현할수 있는 tip) addTextChangeListener를 스틱코드에 등록하면 빠르고 , 편하게 사용하실 수 있습니다.~! 

저는 searchFilter까지 저장해두었어요!

 

 

 

stickode.com/code.html?fileno=9604

 

STICKODE - 코드 등록하기

스틱코드에서 개발에 필요한 전세계의 모든 코드들을 찾아보세요! Java, Android, Kotlin, PHP 등의 수 많은 언어와 플랫폼을 지원합니다.

stickode.com

 

stickode.com/code.html?fileno=9605

 

STICKODE - 코드 등록하기

스틱코드에서 개발에 필요한 전세계의 모든 코드들을 찾아보세요! Java, Android, Kotlin, PHP 등의 수 많은 언어와 플랫폼을 지원합니다.

stickode.com

 

 

결과입니다.

음식 리스트에 닭가슴살 , 피자 , 햄버거 , 제육볶음, 닭갈비, 바지락 칼국수 , 닭볶음탕을 넣어두었습니다.

그 후에 '닭'을 검색했을 때 닭이 포함된 단어인 닭가슴살 , 닭갈비 , 닭볶음탕만 보이는 것을 확인할 수 있습니다.!