android 拼音搜索

本文章为大家介绍一个日常开发中比较常用的一个功能——搜索。

按照数据源所在的位置不同我们可以简单的将搜索分为网络搜索和本地搜索。而本篇文章主要涉及的是本地搜索。

达到的效果:

1、输入文字进行搜索

2、输入文字首字母进行搜索,如搜“张三”可以快捷地输入“zs”进行搜索

实现的思路:

将数据源里的每一项源数据都拿出来与用户输入的搜索关键字进行对比,如果源数据包含搜索关键字则将该数据加到一个集合里保存,这个集合就是我们搜索后的目标数据,将该集合进行展示即可。但有一个问题,那就是搜索时为了达到快速搜索的目的人们往往会输入文字的首字母来代替文字,比如“张三”就会快速输入成“zs”,在这个时候我们就需要采取一些算法来支持这种搜索方式了,至于算法后面会给出代码。

现在我们一起来看看效果:

    

下面是主要类的代码:

首先是工具类,主要是将源数据转换成文字首字母的形式,如“张四未”转为“zsw”,该类目前只支持一级汉字的转换,二级汉字需要大家共同完善!

public class WordUtil {
    static final int GB_SP_DIFF=160;
    // 存放国标一级汉字不同读音的起始区位码
    static final int[] secPosValueList = { 1601, 1637, 1833, 2078, 2274, 2302, 2433, 2594,
        2787, 3106, 3212,3472, 3635, 3722, 3730, 3858, 4027, 4086, 4390, 4558, 4684, 4925,
        5249, 5600 };
    // 存放国标一级汉字不同读音的起始区位码对应读音
    static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 
        'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y', 'z' };

    public static String getSpells(String characters){
                StringBuffer buffer = new StringBuffer();
                for(int i=0;i<characters.length();i++){
                    char ch = characters.charAt(i);
                    if((ch>>7)==0){//判断是否为汉字,如果左移7位为0就不是汉字,否则是汉字
                        buffer.append(ch);
                    }else{
                        char spell = getFirstLetter(ch);
                        buffer.append(String.valueOf(spell));
                    }
                }
                return buffer.toString();
    }
    // 获取一个汉字的首字母
    public static Character getFirstLetter(char ch) {
        byte[] uniCode = null;
        try {
            uniCode = String.valueOf(ch).getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        if (uniCode[0] < 128 && uniCode[0] > 0) { // 非汉字
            return ch;
        } else {
             return convert(uniCode);
        }
    }
    /**
    * 获取一个汉字的拼音首字母。 GB码两个字节分别减去160,转换成10进制码组合就可以得到区位码
    * 例如汉字“你”的GB码是0xC4/0xE3,分别减去0xA0(160)就是0x24/0x43
    * 0x24转成10进制就是36,0x43是67,那么它的区位码就是3667,在对照表中读音为‘n’
    */
    static char convert(byte[] bytes) {
        char result = '-';
        int secPosValue = 0;
        int i;
        for (i = 0; i < bytes.length; i++) {
            bytes[i] -= GB_SP_DIFF;
            }
        secPosValue = bytes[0] * 100 + bytes[1];
        for (i = 0; i < 23; i++) {
            if (secPosValue >= secPosValueList[i] && secPosValue < secPosValueList[i + 1]){
                result = firstLetter[i];
                break;
            }
        }
        return result;
    }
}

ListAdapter,列表适配器,更新搜索列表

public class ListAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<User> datasource; //源数据
    private ArrayList<User> showdata;//显示的数据(符合搜索条件的数据)
    public ListAdapter(Context context){
        this.context = context;
    }
    @Override
    public int getCount() {
        if(showdata == null){
            return 0;
        }
        return showdata.size();
    }
    @Override
    public Object getItem(int arg0) {
        if(showdata != null){
            return showdata.get(arg0);
        }
        return null;
    }
    @Override
    public long getItemId(int arg0) {
        return 0;
    }
    @Override
    public View getView(int position, View view, ViewGroup arg2) {
        ItemViewCache cache = null;
        if(view == null){
            cache = new ItemViewCache();
            view = LayoutInflater.from(context).inflate(R.layout.listview, null);
            cache.name = (TextView)view.findViewById(R.id.name);
            cache.number = (TextView)view.findViewById(R.id.number);
            view.setTag(cache);
        }else{
            cache = (ItemViewCache)view.getTag();
        }
        cache.name.setText(showdata.get(position).getName());
        cache.number.setText(showdata.get(position).getNumble());
        return view;
    }
    //缓存类,重用以达到优化列表的效果
    public class ItemViewCache{
        public TextView name;
        public TextView number;
    }
    public void setDataSource(ArrayList<User> datasource){
        this.datasource = datasource;
        showdata = (ArrayList<User>)datasource.clone();
        this.notifyDataSetInvalidated();
    }
    //对源数据进行搜索
    public void searchData(String word){
        if(word == null || word == ""){
            this.showdata = (ArrayList<User>)this.datasource.clone();
        }else{
            dataFilter(word);
        }
        this.notifyDataSetInvalidated();
    }
    
    private void dataFilter(String word){
        showdata.clear();
        int listsize = datasource.size();
        for(int i = 0;i < listsize; i++){
            User user = datasource.get(i);
            if(user.getName().contains(word)){
                showdata.add(user);
            }else if(WordUtil.getSpells(user.getName()).contains(word.toLowerCase())){
                showdata.add(user);
            }
        }
    }
}

User,列表的数据模型

public class User {
    private String name;
    private String numble;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNumble() {
        return numble;
    }
    public void setNumble(String numble) {
        this.numble = numble;
    }
}

SeachActivity,主界面,搜索框内容更变监听

public class SeachActivity extends Activity {
    private EditText seachEdit;
    private ListView listView;
    private ListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seach);
        init();
    }
    private void init(){
        seachEdit = (EditText)this.findViewById(R.id.search_view);
        listView = (ListView)this.findViewById(R.id.listview);
        adapter = new ListAdapter(this);
        listView.setAdapter(adapter);
        adapter.setDataSource(prepareData());
        seachEdit.addTextChangedListener(new TextWatcher(){
            @Override
            public void afterTextChanged(Editable arg0) {
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.searchData(seachEdit.getText().toString());
            }});
    }
    
    private ArrayList<User> prepareData(){
        ArrayList<User> datalist = new ArrayList<User>();
        User user = new User();
        user.setName("张三");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("张三丰");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("张四未");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("张为剑");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("王晨");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("李联接");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("洪进报");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("王包墙");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("宋组因");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("张雪有");
        user.setNumble("13757798098");
        datalist.add(user); 
        
        user = new User();
        user.setName("刘得滑");
        user.setNumble("13757798098");
        datalist.add(user); 
        return datalist;
    }

}

 

上面的代码我打包共享到CSDN上了,需要的朋友可自行下载,地址如下:

http://download.csdn.net/detail/zhuiji7/5845721#comment

 

版权归“追击7号”所有,转载请注明出处http://blog.csdn.net/zhuiji7/article/details/9668125

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值