iT邦幫忙

2023 iThome 鐵人賽

DAY 27
0

前言
這裡我們會建立一個模糊搜尋的簡單範本,這裡會使用RecycleView和EditText的監聽器,在我這邊的使用方法目的是怎麼模糊搜尋,如果想要像Google一個的選單的話,要使用其他物件來做使用。

功能

------部局的部分------

主畫面

main_activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="0sp"
            android:layout_weight="1"
            android:text="My Obscure Search"
            android:gravity="center"
            android:background="@color/blue"
            android:textSize="40sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0sp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/editTextText"
                android:layout_width="0sp"
                android:layout_height="match_parent"
                android:layout_weight="7.5"
                android:ems="10"
                android:inputType="text" />

            <Button
                android:id="@+id/button"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2.5"
                android:background="@color/yellow"
                android:text="Search"
                android:textColor="@color/black"
                android:textSize="17sp" />
        </LinearLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="match_parent"
            android:layout_height="0sp"
            android:layout_weight="8" />

    </LinearLayout>
</LinearLayout>

RecycleView的子畫面

recycleview_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:gravity="left"
        android:textColor="@color/black"
        android:textSize="40sp" />
</LinearLayout>

-------主程式-------

MainActivity

package com.example.search;

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.util.Log;
import android.view.View;
import android.widget.EditText;


import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recycleView;
    private EditText search_context_editText;
    private MyAdapter adapter;
    List<String> baseDataList = new ArrayList<>(); //這裡當作資料庫做使用
    List<String> searchDataList = new ArrayList<>(); //搜尋到的資料
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();//初始化
        searchListener_EditText();//模糊搜尋用EditText的監聽器來做處裡
    }
    private void initialize(){
        search_context_editText = findViewById(R.id.editTextText);
        recycleView = findViewById(R.id.recycleView);
        generateFalseData(baseDataList);//建立假資料
        setRecycleView();
    }

    private void searchListener_EditText(){
        search_context_editText.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) {
                searchDataList.clear();//清除資料 準備重新放入新的資料進去
                Log.d("Size",Integer.toString(searchDataList.size()));
                String searchResult= String.valueOf(search_context_editText.getText());
                Log.d("editText",searchResult);
                if(searchResult.length() != 0){
                    for(int j = 0; j < baseDataList.size();j++) {
                        String baseDataItem = baseDataList.get(j);
                        if (baseDataItem.toLowerCase().contains(searchResult.toLowerCase())) {
                            searchDataList.add(baseDataItem);
                        }
                    }
                }
                Log.d("ResultSize",Integer.toString(searchDataList.size()));
                adapter.putData(searchDataList);
            }


            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
    //設定RecycleView
    private void setRecycleView(){
        // 將數據添加到 MyAdapter建構元裡 中
        adapter = new MyAdapter(this, searchDataList);
        recycleView.setAdapter(adapter);

        // 設置線性佈局管理器
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recycleView.setLayoutManager(layoutManager);
    }
    //建立假資料
    public void generateFalseData(List<String> dataList){
        String falseData[] = {"Apple","Strawberry","Banana","Orange"
                              ,"Pineapple","guava","Bennet","Bilberry","Bilberry"};

        // 生成假資料
        for (int i = 0; i < falseData.length; i++) {
            dataList.add(falseData[i]);
        }
    }
}

RecycleView的調適器

MyAdapter

package com.example.search;

import android.content.Context;
import android.util.Log;
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.List;

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

    private List<String> dataList;
    private Context context;

    public MyAdapter(Context context, List<String> dataList) {
        this.context = context;
        this.dataList = dataList;
        //Log.d("dataListSize", Integer.toString(dataList.size()));
    }
    public void putData(List<String> dataList){
        this.dataList = dataList;
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycleview_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String itemData = dataList.get(position);
        //Log.d("itemData:",itemData);
        holder.data_textView.setText(itemData);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView data_textView;
        public ViewHolder(View itemView) {
            super(itemView);
            data_textView = itemView.findViewById(R.id.textView);
        }
    }
}

-------程式碼解說-------

1.searchListener_EditText():用EditText的監聽器來監聽文字的變化,可以看到我會先清除我放入模糊搜尋的資料(ArrayList),在重新放入新的資料資進去。

  • if(baseDataItem.toLowerCase().contains(searchResult.toLowerCase())):如果我的資料庫端的資料有包含到搜尋的資料的話就放入資料到膜糊搜尋的arrayList。
private void searchListener_EditText(){
        search_context_editText.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) {
                searchDataList.clear();//清除資料 準備重新放入新的資料進去
                Log.d("Size",Integer.toString(searchDataList.size()));
                String searchResult= String.valueOf(search_context_editText.getText());
                Log.d("editText",searchResult);
                if(searchResult.length() != 0){
                    for(int j = 0; j < baseDataList.size();j++) {
                        String baseDataItem = baseDataList.get(j);
                        if (baseDataItem.toLowerCase().contains(searchResult.toLowerCase())) {
                            searchDataList.add(baseDataItem);
                        }
                    }
                }
                Log.d("ResultSize",Integer.toString(searchDataList.size()));
                adapter.putData(searchDataList);
            }


            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

總結
本篇章教學使用膜糊搜尋的部分,不過這只是模糊搜尋的其中一個方法,還有其他更好的寫法,這可能會牽涉到演算法的部分,本篇章就到這邊。


上一篇
Day26 - SharedPreferences 記住帳密
下一篇
Day28 - 使用Firebase與Android studio實現登入(上篇)
系列文
Android studio使用過程與開發說明30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言