美文网首页Android
RecyclerView使用Filterable筛选数据并高亮

RecyclerView使用Filterable筛选数据并高亮

作者: 明日未期 | 来源:发表于2020-03-17 00:15 被阅读0次

效果


Class

MainActivity.java
SecondActivity.java

Layout

activity_main.xml
activity_second.xml
item.xml

Adapter

MyAdapter.java

JavaBean

People.java

activity_main.xml

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll"/>
        <EditText
            android:layout_width="match_parent"
            android:ems="10"
            android:layout_height="wrap_content"
            android:id="@+id/search"/>
    </android.support.design.widget.AppBarLayout>
    
    <android.support.v7.widget.RecyclerView
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/recycler_view"/>
</android.support.design.widget.CoordinatorLayout>

activity_second.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
</LinearLayout>

item.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:id="@+id/item_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/name"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text"
        android:layout_marginTop="4dp"
        android:id="@+id/age"/>

</LinearLayout>

People.java

public class People {
    private String name;

    private int age;

    public People(String name, int age){
        this.name=name;
        this.age=age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RecyclerView rv;
    private EditText et;

    private List<People> data = new ArrayList<>();
    private MyAdapter adapter;

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


    private void bindViews() {
        toolbar = findViewById(R.id.toolbar);
        rv = findViewById(R.id.recycler_view);
        et = findViewById(R.id.search);
    }

    private void initData() {
        setSupportActionBar(toolbar);

        data.add(new People("小红", 12));
        data.add(new People("小明", 15));
        data.add(new People("李磊", 16));
        data.add(new People("红红", 13));
        data.add(new People("艾玛", 14));
        data.add(new People("李医生", 14));
        data.add(new People("红钱", 12));
        data.add(new People("喔哦", 11));
    }

    private void handleRecyclerView() {
        adapter = new MyAdapter(this, data);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(adapter);

        et.addTextChangedListener(new TextWatcher(){

                @Override
                public void beforeTextChanged(CharSequence p1, int p2, int p3, int p4) {
                }

                @Override
                public void onTextChanged(CharSequence p1, int p2, int p3, int p4) {
                    adapter.getFilter().filter(p1.toString());
                }

                @Override
                public void afterTextChanged(Editable p1) {
                }
            });
    }
}

SecondActivity.java

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class SecondActivity extends AppCompatActivity {

    private String data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent intent = getIntent();
        data = intent.getStringExtra("data");
        Toast.makeText(this, data, Toast.LENGTH_LONG).show();

    }

    public static void actionStart(Context context, String str) {
        Intent intent = new Intent(context, SecondActivity.class);
        intent.putExtra("data", str);
        context.startActivity(intent);
    }

}

MyAdapter.java

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    List<People> mDataList = new ArrayList<>();
    List<People> filterList = new ArrayList<>();
    private Context mContext;
    private People people;

    private OnItemClickListener listener;
    private String charStr;

    static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout parentView;
        TextView nameView, ageView;
        public ViewHolder(View view) {
            super(view);
            parentView = view.findViewById(R.id.item_parent);
            nameView = view.findViewById(R.id.name);
            ageView = view.findViewById(R.id.age);
        }
    }

    public MyAdapter(Context context, List<People> datas) {
        this.mContext = context;
        this.mDataList = datas;
        this.filterList = datas;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {
        people = filterList.get(position);

        if (!TextUtils.isEmpty(charStr)) {
            SpannableString str = matchSearch(Color.RED, people.getName(), charStr);
            holder.nameView.setText(str);
        } else {
            holder.nameView.setText(people.getName());

        }
        holder.ageView.setText(people.getAge() + "");
        holder.parentView.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View p1) {
                    SecondActivity.actionStart(mContext, filterList.get(position).getName());
                }
            });
    }

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

    @Override
    public Filter getFilter() {
        return new Filter(){

            @Override
            protected Filter.FilterResults performFiltering(CharSequence charsequence) {
                charStr = charsequence.toString();
                if (TextUtils.isEmpty(charStr)) {
                    filterList = mDataList;
                } else {
                    List<People> filteredList = new ArrayList<>();
                    for (int i=0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getName().contains(charStr)) {
                            filteredList.add(mDataList.get(i));
                        }
                    }
                    filterList = filteredList;
                }
                FilterResults filterRes = new FilterResults();
                filterRes.values = filterList;
                return filterRes;
            }

            @Override
            protected void publishResults(CharSequence p1, Filter.FilterResults p2) {
                filterList = (List<People>) p2.values;
                notifyDataSetChanged();
            }       

        };
    }

    private SpannableString matchSearch(int color, String str, String key) {
        SpannableString ss = new SpannableString(str);
        Matcher m = Pattern.compile(key).matcher(ss);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    public interface OnItemClickListener {
        public void onItemClick(String str);
    }


    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

}

相关文章

网友评论

    本文标题:RecyclerView使用Filterable筛选数据并高亮

    本文链接:https://www.haomeiwen.com/subject/esmaehtx.html