Android之如何实现通讯录的搜索并且让匹配到的数据变颜色

不废话,先爆照

Android之如何实现通讯录的搜索并且让匹配到的数据变颜色_第1张图片


Android之如何实现通讯录的搜索并且让匹配到的数据变颜色_第2张图片


第一步:实现搜索

                   已经实现了通讯录功能,但是需要搜索,可以支持中文名字搜索,写入电话号码搜索,还有名字拼音,以及名字第一个字的首字母来搜索,这里介绍名字搜索,然后数据是我们公司TCL(020)所有员工的信息,目前还没有写到后台请求数据,只把数据放在XML文件里面,然后解析出来,放入集合。

首先我们需要了解编辑器监听器(textwatcher)

 class MyTextWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            boolean boo=s.toString().matches("^[0-9]*$");
            if(boo){
                checkUserByChanese(s,Constant.MONILESEARCH);
            }else{
                checkUserByChanese(s,Constant.NAMESEARCH);
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    }

然后这是我搜索类里面的全部代码

package com.kuyu.kuyucontact.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.kuyu.kuyucontact.R;
import com.kuyu.kuyucontact.app.MyApplication;
import com.kuyu.kuyucontact.ui.adapter.ContactListItemAdapter;
import com.kuyu.kuyucontact.ui.view.PinnedSectionListView;
import com.kuyu.kuyucontact.util.Constant;

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

/**
 * Created by Administrator on 2015/12/10.
 */
public class SearchUser extends AppCompatActivity {
    private EditText etSearch;
    private PinnedSectionListView mListView;
    protected MyApplication mMyApplication = MyApplication.getInstance(this);
    private List<ContactListItem> contactListItemList;
    private List<ContactListItem> resultListItemList = new ArrayList<ContactListItem>();
    private List<String> nameList;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.search);
        etSearch = (EditText) findViewById(R.id.search_text);
        mListView = (PinnedSectionListView) findViewById(R.id.lv_contact_search);
        etSearch.addTextChangedListener(new MyTextWatcher());
        contactListItemList = mMyApplication.getContactListItemLis();
    }

    class MyTextWatcher implements TextWatcher {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            boolean boo=s.toString().matches("^[0-9]*$");
            if(boo){
                checkUserByChanese(s,Constant.MONILESEARCH);
            }else{
                checkUserByChanese(s,Constant.NAMESEARCH);
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    }

    @SuppressLint("NewApi")
    private void initializeAdapter(List<ContactListItem> userList,CharSequence s,String way) {
//        mListView.setAdapter(new ContactListItemAdapter(userList, this))
        mListView.setAdapter(new ContactListItemAdapter(userList, this, s.toString(), way));
    }

    /**
     * 按中文搜索
     */
    public void checkUserByChanese(CharSequence s,String way){
        resultListItemList.clear();
        for (ContactListItem contactListItem : contactListItemList) {
            if (contactListItem.getItemType() == ContactListItem.CONTACT_ITEM_TYPE_USER) {//筛选名字
                if(Constant.NAMESEARCH.equals(way)){
                    if (contactListItem.getmContactUser().getUsername().contains(s)) {
                        resultListItemList.add(contactListItem);
                    }
                }else if(Constant.MONILESEARCH.equals(way)){
                    if (contactListItem.getmContactUser().getMobileNo().contains(s)) {
                        resultListItemList.add(contactListItem);
                    }
                }
            }
        }//当文本框里面没有内容的时候清空resultListItemList
        if (contactListItemList.size() - resultListItemList.size() == Constant.NAMEHASPINGYING) {
            resultListItemList.clear();
        }
        if (resultListItemList != null && s!=null) { //设置adapter
            initializeAdapter(resultListItemList,s,way);
        }
    }

}

这是我代码里面实现的,当我们的编辑器设置这个监听的时候,每次我么输入的内容就会触发onTextChanged()这个函数,里面的参数 s就是编辑器里面的内容,然后拿到编辑器里面的内容与我们的数据做出匹配,然后把匹配到的数据,放入adapter


第二步:实现匹配到的数据变颜色

这里需要介绍下SpannableString显示复合文本和ForegroundColorSpan  文本颜色
先看下这个函数



然后简单例子

SpannableString spanString = new SpannableString("背景色");    
    BackgroundColorSpan span = new BackgroundColorSpan(Color.RED);    
    spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
    tv.append(spanString);    

setSpan这个函数已经图片介绍了,start  end 分别是变颜色的起始坐标,span是设置背景颜色

我的adapter里面的关键代码如下
  String username=mContactUser.getUsername();
                    int index=username.indexOf(result);
                    Log.i("index",index+"");
                    SpannableString span = new SpannableString(username);
                    span.setSpan(new ForegroundColorSpan(Color.RED), index, index+result.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.userName.setText(username);
                    viewHolder.userName.setText(span);  //设置字体变颜色
                    String mobileNo = mContactUser.getMobileNo();
                    String mobileHandle = mobileNo ==null || mobileNo.equals("null") ?"":mContactUser.getMobileNo();
                    viewHolder.mobile.setText(mobileHandle);
其中result是编辑器里面的内容,username是集合里面的数据,得到匹配的下标,然后这是颜色,然后注入到视图里面去

下面是ContactListItemAdapter.java类
package com.kuyu.kuyucontact.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.kuyu.kuyucontact.R;
import com.kuyu.kuyucontact.ui.ContactListItem;
import com.kuyu.kuyucontact.ui.ContactUser;
import com.kuyu.kuyucontact.ui.view.PinnedSectionListView;
import com.kuyu.kuyucontact.util.Constant;

import java.util.List;

/**
 * Created by fish on 15/12/2.
 */
public class ContactListItemAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter {

    protected List<ContactListItem> list;
    protected Context ctx;
    protected LayoutInflater inflater = null;
    protected int rowContactId = R.layout.list_view_contact;
    protected String way=Constant.NORMALSHOW;
    protected String result; //需要匹配字符串


    public ContactListItemAdapter(List<ContactListItem> list, Context ctx) {
        this.list = list;
        this.ctx = ctx;
        inflater = LayoutInflater.from(ctx);
    }
    public ContactListItemAdapter(List<ContactListItem> list, Context ctx,String result,String way) {
        this.list = list;
        this.ctx = ctx;
        inflater = LayoutInflater.from(ctx);
        this.result=result;
        this.way=way;
    }

    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) {
        if (view == null) {
            view = inflater.inflate(rowContactId, null);
        }
        ViewHolder viewHolder = null;
        if (view.getTag() == null) {
            viewHolder = new ViewHolder();
            viewHolder.avatar = (ImageView) view.findViewById(R.id.iv_avatar);
            viewHolder.userName = (TextView) view.findViewById(R.id.tv_username);
            viewHolder.mobile = (TextView) view.findViewById(R.id.tv_mobile);
            viewHolder.indexView = (TextView) view.findViewById(R.id.tv_index);
            viewHolder.userView = (RelativeLayout) view.findViewById(R.id.rl_user);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        ContactListItem mContactListItem = list.get(i);
        if (mContactListItem.getItemType() == ContactListItem.CONTACT_ITEM_TYPE_INDEX){
            viewHolder.indexView.setVisibility(View.VISIBLE);
            viewHolder.userView.setVisibility(View.GONE);
            viewHolder.indexView.setText(mContactListItem.getIndexLetter());
        }else{
            viewHolder.indexView.setVisibility(View.GONE);
            viewHolder.userView.setVisibility(View.VISIBLE);
            ContactUser mContactUser = mContactListItem.getmContactUser();
            if (mContactUser != null) {
//            viewHolder.avatar.setBackground(mContactUser.getUsername());
                if(way.equals(Constant.NORMALSHOW)){
                viewHolder.userName.setText(mContactUser.getUsername());
                String mobileNo = mContactUser.getMobileNo();
                String mobileHandle = mobileNo ==null || mobileNo.equals("null") ?"":mContactUser.getMobileNo();
                viewHolder.mobile.setText(mobileHandle);
                }else if(Constant.NAMESEARCH.equals(way)){   //中文匹配的时候给匹配到的字加颜色
                    String username=mContactUser.getUsername();
                    int index=username.indexOf(result);
                    Log.i("index",index+"");
                    SpannableString span = new SpannableString(username);
                    span.setSpan(new ForegroundColorSpan(Color.RED), index, index+result.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.userName.setText(username);
                    viewHolder.userName.setText(span);  //设置字体变颜色
                    String mobileNo = mContactUser.getMobileNo();
                    String mobileHandle = mobileNo ==null || mobileNo.equals("null") ?"":mContactUser.getMobileNo();
                    viewHolder.mobile.setText(mobileHandle);
                }else if(Constant.MONILESEARCH.equals(way)){   //电话号码匹配的时候给匹配到的字加颜色
                    viewHolder.userName.setText(mContactUser.getUsername());
                    String mobileNo = mContactUser.getMobileNo();
//                    String mobileHandle = mobileNo ==null || mobileNo.equals("null") ?"":mContactUser.getMobileNo();
                    int index=mobileNo.indexOf(result,0);
                    Log.i("mobileNo",mobileNo);
                    Log.i("result",result);
                    Log.i("tel_index",index+"");
                    SpannableString span = new SpannableString(result);
//                    span.setSpan(new ForegroundColorSpan(Color.RED), index, index + result.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.mobile.setText(mobileNo);
//                    viewHolder.mobile.setText(span);  //设置匹配到的电话号码变颜色
                }
            }
        }
        return view;
    }

    //判断是否固定
    @Override
    public boolean isItemViewTypePinned(int viewType) {
        return viewType == ContactListItem.CONTACT_ITEM_TYPE_INDEX;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return ((ContactListItem)getItem(position)).getItemType();
    }

    class ViewHolder {
        public ImageView avatar;
        public TextView userName;
        public TextView mobile;
        public TextView indexView;
        public RelativeLayout userView;
    }
}

其它搜索实现原理类似。

 


你可能感兴趣的:(android,通讯录的搜索,配到的数据变颜色)