android-View之搜索功能的实现

  • 现在很多的app中都有搜索的功能。也就是说搜索栏下面有一个列表,列表中放的内容我们可以在搜索框中输入你想要搜索的内容,这时候,下面的列表就会出现你想要的内容。如图:


    image.png
  • xml





    

    

        

            

        


        

        

            

                
            

            

        

    

    

    



  • adapter 这个类实现了Filterable接口,然后重写了getFilter()方法,在adapter中定义了一个内部类MyFilter继承Filter类,并重写相关方法,实现数据的过滤。

public class AppealNameListAdapter extends BaseAdapter implements Filterable
{

    private List list = new ArrayList();
    private Context context;
    private List original;
    private FilterListener listener = null;// 接口对象





    public AppealNameListAdapter(List list, Context context, FilterListener listener){
        this.list = list;
        this.context = context;
        this.listener=listener;

    }



    @Override
    public Filter getFilter()
    {
        return new MyFilter();
    }

    @Override
    public int getCount()
    {
        return list.size();
    }

    @Override
    public Object getItem(int i)
    {
        return list.get(i);
    }

    @Override
    public long getItemId(int i)
    {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup)
    {
        ViewHolder holder = null;
        if(view==null){
            view= LayoutInflater.from(context).inflate(R.layout.item_other_appeal, null);
            holder = new ViewHolder();
            holder.tv_name = (TextView) view.findViewById(R.id.tv_item_name);
            holder.tv_number = (TextView) view.findViewById(R.id.tv_item_number);
            view.setTag(holder);

        }
        holder = (ViewHolder) view.getTag();
        holder.tv_name.setText(list.get(i).getName());
        holder.tv_number.setText(list.get(i).getNumber());
        return view;
    }


    class MyFilter extends Filter
    {

        /**
         * 过滤数据
         * @param charSequence
         * @return
         */
        @Override
        protected FilterResults performFiltering(CharSequence charSequence)
        {
            FilterResults results = new FilterResults();

            if(original==null){
                original=new ArrayList(list);
            }

            if (TextUtils.isEmpty(charSequence))
            {
                results.values = original;
                results.count = original.size();

            } else
            {
                String prefixString = charSequence.toString().toLowerCase();
                // 创建集合保存过滤后的数据
                List mList = new ArrayList();
                // 遍历原始数据集合,根据搜索的规则过滤数据
                for (OtherAppealNameListBean s : original)
                {

                    if(s.getNumber().startsWith(prefixString)||s.getName().startsWith(prefixString)){
                        mList.add(s);
                    }


                }
                results.values = mList;
                results.count = mList.size();


            }


            return results;
        }

        /**
         * 该方法用来刷新用户界面,根据过滤后的数据重新展示列表
         * @param charSequence
         * @param filterResults
         */
        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults)
        {
            list = (List) filterResults.values;
            if(listener != null){
                listener.getFilterData(list);
            }

            if (filterResults.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }

        }

    }



    class ViewHolder {
        TextView tv_name;
        TextView tv_number;
    }

}
  • activity

 private void initView()
    {
        setOperationVisibility(View.GONE);
        Utils.switchKeyboard(this, mEtSearch, true);
        mMSV.setViewForState(R.layout.layout_empty_view_teacher_search, MultiStateView.VIEW_STATE_EMPTY);
        mMSV.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mSRL.setRefreshing(false);
    }
    private void initData()
    {
        mDatas = new ArrayList<>();
        mAdapter = new AppealNameListAdapter(mDatas, this, new FilterListener()
        {
            @Override
            public void getFilterData(List list)
            {
                setItemClick(list);
            }
        });
        mListView.setAdapter(mAdapter);
        mPresenter.getAppealNameList();


    }

private void initEvent()
    {
        setItemClick(mDatas);

        mEtSearch.setOnEditorActionListener((v, actionId, event) ->
        {
            return true;
        });

        mEtSearch.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)
            {
                mAdapter.getFilter().filter(mEtSearch.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                setOperationVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });


    }


   private void setItemClick(List list)
    {
        mListView.setOnItemClickListener((parent, view, position, id) ->
        {
            OtherAppealNameListBean bean = list.get(position);
                EventBus.getDefault().post(new OtherAppealSearchEvent(mEventTag, bean));
                finish();
            }


    }

  /**
     * 取消 显示
     *
     * @param visible
     */
    private void setOperationVisibility(int visible)
    {
        mIvClear.setVisibility(visible);
    }



    /**
     * 隐藏展示 键盘
     *
     * @param activity
     * @param editText
     * @param showOrhide
     */
    public static void switchKeyboard(Activity activity, EditText editText, boolean showOrhide)
    {

        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (showOrhide)
        {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            imm.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
        } else
        {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

  • 接口代码 (搜索后的数据没有变,点击后还是显示原来的数据。)

/**
 * Created by hm on 2019/3/15.
 * 获取过滤后的数据
 */
public interface FilterListener
{
    void getFilterData(List list);// 获取过滤后的数据

}

  • 注 ( (刚开始搜索完成后,点击搜索后的数据,但是显示的是原来的数据,那么就是数据源没有变、而这个回调,就是为了解决这个问题的,拿到过滤后的数据源,对新的数据源进行操作即可很好的解决这个问题)。)

image.png

你可能感兴趣的:(android-View之搜索功能的实现)