Android中使用Filterable實現匹配搜索

接上文,上文地址:https://blog.csdn.net/JiYaRuo/article/details/82285711

GitHup地址:https://github.com/JiYaRuo/LocalVagueSearchData

1. SearchNeighbourActivity類

/**
 * Created by JiYaRuo.
 * 好友搜索頁面
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener{

    //返回按鈕
    private ImageView ivBack;
    //搜索文本
    private TextView btnSearch;
    //搜索框
    private EditText ev_search_friend;
    //展示所搜索出來好友列表的rv
    private RecyclerView rv_search_user;
    //總的好友列表集合
    private List<User> mNeighbourFriendItemTotalList;
    //搜索出來的好友列表集合
    private List<User> mSearchNeighbourFriendItemList = new ArrayList<>();
    //搜索列表rv適配器
    private SearchNeighbourRvAdapter searchNeighbourRvAdapter;
    //輸入法管理器
    private InputMethodManager inputMethodManager;


    @Override
    protected void initUI() {
        ScreenUtils.setStatusBarBackground(this);
        setContentView(R.layout.activity_search);
        try {
            //獲取所有聯繫人數據源集合
            mNeighbourFriendItemTotalList = FriendSListActivity.mDatas;
            //初始化輸入法管理器
            inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            //初始化控件
            initView();
        } catch (Exception e) {
        }
    }

    /**初始化控件*/
    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        btnSearch = findViewById(R.id.btn_search_cancle);
        ivBack.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        ev_search_friend = findViewById(R.id.ev_search_friend);
        rv_search_user=findViewById(R.id.rv_search_user);
        setAdapter();
        ev_search_friend.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(!NetUtils.isConnected(SearchNeighbourActivity.this)){
                    ToastUtils.show("當前網絡連接已經斷開,請檢查您的網絡設置");
                    return false;
                }

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //先隱藏鍵盤
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(ev_search_friend.getApplicationWindowToken(), 0);
                    }
                 searchNeighbourRvAdapter.getFilter().filter(ev_search_friend.getText().toString()); // 當數據改變時,調用過濾器;
                }
                //記得返回false
                return false;
            }
        });
        ev_search_friend.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) {
                searchNeighbourRvAdapter.getFilter().filter(s); // 當數據改變時,調用過濾器;
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**設置適配器*/
    private void setAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_search_user.setLayoutManager(manager);
        searchNeighbourRvAdapter = new SearchNeighbourRvAdapter(R.layout.letter_list, mSearchNeighbourFriendItemList, mNeighbourFriendItemTotalList);
        rv_search_user.setAdapter(searchNeighbourRvAdapter);
        //final View view = LayoutInflater.from(this).inflate(R.layout.empty_search_friend_laayout, null);
        //view.setLayoutParams(new RecyclerView.LayoutParams(MATCH_PARENT,MATCH_PARENT));
        //searchNeighbourRvAdapter.setEmptyView(view);
        searchNeighbourRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        overridePendingTransition(0,0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_search_cancle:
                finish();
                break;
        }
    }

2.佈局頁面:activity_search

<?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="match_parent"
    android:orientation="vertical">
    <View
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_20">
    </View>
    <RelativeLayout
        android:gravity="center_vertical"
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_52">
        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:paddingLeft="@dimen/dp_4"
            android:paddingRight="@dimen/dp_4"
            android:src="@mipmap/icon_back" />
        <EditText
            android:id="@+id/ev_search_friend"
            android:paddingLeft="@dimen/dp_10"
            android:drawablePadding="@dimen/dp_5"
            android:hint="搜索"
            android:inputType="text"
            android:layout_centerVertical="true"
            android:textSize="@dimen/sp_14"
            android:gravity="center_vertical"
            android:maxLines="1"
            android:drawableLeft="@mipmap/search_goods"
            android:layout_marginLeft="@dimen/dp_37"
            android:layout_marginRight="@dimen/dp_53"
            android:paddingTop="@dimen/dp_4"
            android:paddingBottom="@dimen/dp_4"
            android:background="@drawable/search_goods"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/btn_search_cancle"
            android:text="取消"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/dp_10"
            android:gravity="center_vertical"
            android:textColor="#6d6d6d"
            android:textSize="@dimen/sp_14"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
    </RelativeLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_search_user"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

3.搜索的適配器SearchNeighbourRvAdapter

/**
 * Created by JiYaRuo on 2018/8/8.
 */

public class SearchNeighbourRvAdapter extends BaseQuickAdapter<NeighbourFriendItem, BaseViewHolder> implements Filterable {

    private List<User> mNeighbourFriendItemTotalList = new ArrayList<>();//總列表集合
    private List<User> mSearchNeighbourFriendItemList = new ArrayList<>();//搜索出來列表集合
    private SearchUserFilter searchUserFilter;//搜索過濾器
    private boolean ifNotifyData = false;
    int searchStartIndex;
    int searchLastIndex;


    public SearchNeighbourRvAdapter(int layoutResId, @Nullable List<User> searchNeighbourFriendItemList, List<User> totalNeighbourFriendItemList) {
        super(layoutResId, searchNeighbourFriendItemList);
        this.mSearchNeighbourFriendItemList = searchNeighbourFriendItemList;
        this.mNeighbourFriendItemTotalList = totalNeighbourFriendItemList;
    }

    @Override
    protected void convert(BaseViewHolder helper, User item) {
        try {
            if (ifNotifyData) {
                helper.setText(R.id.tv_user_name, item.getUserName());
                helper.setText(R.id.tv_user_sign, item.getUserSign());
                Glide.with(mContext).load(item.getUserImg()).into((ImageView) helper.getView(R.id.iv_user_img));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Filter getFilter() {
        if (searchUserFilter == null) {
            searchUserFilter = new SearchUserFilter();
        }
        return searchUserFilter;
    }

    class SearchUserFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            //需要監聽的字符
            if (constraint == null || constraint.length() == 0) {
                mSearchNeighbourFriendItemList.clear();
                results.values = mSearchNeighbourFriendItemList;
                results.count = mSearchNeighbourFriendItemList.size();
            } else {
                mSearchNeighbourFriendItemList.clear();
                //需要過濾的總集合
                for (User p : mNeighbourFriendItemTotalList) {
                    if (p.getUserName().contains(constraint)) {
                        mSearchNeighbourFriendItemList.add(p);
                    }
                }
                results.values = mSearchNeighbourFriendItemList;
                results.count = mSearchNeighbourFriendItemList.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mSearchNeighbourFriendItemList = (List<NeighbourFriendItem>) results.values;
            ifNotifyData = true;
            for (int i = 0; i < mSearchNeighbourFriendItemList.size(); i++) {
                String userName = mSearchNeighbourFriendItemList.get(i).getUserName();
                searchStartIndex = userName.indexOf(constraint.toString());
                searchLastIndex = searchStartIndex + constraint.length();
            }
            notifyDataSetChanged();
        }
    }

4.搜索rv的item佈局:letter_list

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:gravity="center_vertical"
    android:background="#fff"
    android:paddingLeft="12dp"
    android:paddingRight="12dp"
    android:layout_height="@dimen/dp_63">
    <ImageView
        android:id="@+id/iv_user_img"
        android:layout_width="@dimen/dp_48"
        android:layout_height="@dimen/dp_48" />
    <LinearLayout
        android:orientation="vertical"
        android:paddingTop="@dimen/dp_8"
        android:paddingBottom="@dimen/dp_8"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_user_name"
            android:layout_marginLeft="10dp"
            android:textColor="#2f2f2f"
            android:textSize="@dimen/sp_16"
            android:maxLines="1"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:layout_weight="1.2"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/dp_0" />
        <TextView
            android:id="@+id/tv_user_sign"
            android:maxLines="1"
            android:ellipsize="end"
            android:textColor="#9e9e9e"
            android:textSize="@dimen/sp_14"
            android:layout_marginLeft="10dp"
            android:gravity="center_vertical"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/dp_0" />
    </LinearLayout>
</LinearLayout>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章