Android 联系人字母排序(仿微信)

现在很多APP只要涉及到联系人的界面,几乎都会采取字母排序以及导航的方式。作为程序猿,这种已经普及的需求还是需要学习的,于是小生开始了在网上默默的学习之路,网上学习的资料质量参差不齐,不过也有很不错的文章,文章后面分享给大家。这篇文章,仅是小生在学习之后,自己独立编写与总结吧。废话不多说先上效果图。

从界面上看,整个实现效果有两个重点:

  1. 实现字母分类。
  2. 实现右侧的字母导航。

我们先一个一个来了解解决方案,再上代码。

实现字母分类:

字母分类又分为三个小要点:一个是将中文转化为拼音,一个是实现按照字母的顺序排序,另一个是字母只显示在具有相同首字母中文的第一个前面。

1、将中文转化为拼音,这里使用了一个工具包,即pinyin4j-2.5.0.jar。官网地址:http://pinyin4j.sourceforge.net/

点击下载,导入项目即可。(至于教程,网上很多)

在这里我们只需要使用将中文转换成拼音的代码即可。

PinyinUtils.java

public static String getPingYin(String inputString) {
  HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
  format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
  format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
  format.setVCharType(HanyuPinyinVCharType.WITH_V);
  char[] input = inputString.trim().toCharArray();
  String output = "";
  try {
    for (char curchar : input) {
      if (java.lang.Character.toString(curchar).matches("[\\u4E00-\\u9FA5]+")) {
        String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, format);
        output += temp[0];
      } else
        output += java.lang.Character.toString(curchar);
    }
  } catch (BadHanyuPinyinOutputFormatCombination e) {
    e.printStackTrace();
  }
  return output;
}

2、实现按照字母的顺序排序,使用的是JAVA自带的Comparator接口,利用之前获取到的中文拼音,得到首字母并根据ascii值来实现排序。

private int sort(PersonBean lhs, PersonBean rhs) {
  // 获取ascii值
  int lhs_ascii = lhs.getFirstPinYin().toUpperCase().charAt(0);
  int rhs_ascii = rhs.getFirstPinYin().toUpperCase().charAt(0);
  // 判断若不是字母,则排在字母之后
  if (lhs_ascii < 65 || lhs_ascii > 90)
    return 1;
  else if (rhs_ascii < 65 || rhs_ascii > 90)
    return -1;
  else
    return lhs.getPinYin().compareTo(rhs.getPinYin());
}

3、字母只显示在具有相同首字母中文的第一个前面。这里算是一个小技巧,这里字母显示的布局与中文名字的布局都是存放在ListView的item的布局中的。item的布局如下:

<?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" >
  <!-- 这个TextView就是显示字母的 -->
  <TextView
    android:id="@+id/tv_lv_item_tag"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:background="#e6e6e6"
    android:gravity="center_vertical"
    android:paddingLeft="10dip"
    android:text="Z"
    android:visibility="visible" />
  <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <View 
      android:id="@+id/view_lv_item_line"
      android:layout_width="match_parent"
      android:layout_height="0.5dip"
      android:background="#174465"
      android:layout_marginLeft="10dip"
      android:layout_marginRight="20dip"
      />
    <ImageView
      android:id="@+id/iv_lv_item_head"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/ic_launcher"
      android:layout_below="@id/view_lv_item_line"
      android:layout_marginLeft="5dp" />
    <TextView 
      android:id="@+id/tv_lv_item_name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerVertical="true"
      android:layout_toRightOf="@id/iv_lv_item_head"
      android:layout_marginLeft="5dip"
      android:text="周华健"/>
  </RelativeLayout>
</LinearLayout>

而判断是否需要显示字母,是通过判断当前item的position是否等于第一个出现item对应的中文首字母的索引。如果相等,则说明是第一次出现,便需要显示字母,否则不显示字母。而这样的判断,有一个前提,那就是中文拼音的排序必须是按照字母顺序排序的,这就是我们在上一步排序的必要。

实现右侧的字母导航:

右侧的字母导航,其本质就是一个自定义View。除了绘制界面之外,需要注意的就是触摸事件的处理,还有回调机制(这个很多地方都会用到)的使用。这个比较重要,直接上代码吧。

package com.suse.contact;
import android.content.Context;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.graphics.Typeface;  
import android.graphics.drawable.ColorDrawable;  
import android.util.AttributeSet;  
import android.view.MotionEvent;  
import android.view.View;  
import android.widget.TextView;
public class SideBar extends View {
  // 触摸事件  
  private OnTouchingLetterChangedListener onTouchingLetterChangedListener;  
  // 26个字母  
  public static String[] A_Z = { "A", "B", "C", "D", "E", "F", "G", "H", "I",  
      "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
      "W", "X", "Y", "Z", "#" };  
  private int choose = -1;// 选中  
  private Paint paint = new Paint();  
  private TextView mTextDialog;  
  /** 
   * 为SideBar设置显示字母的TextView 
   * @param mTextDialog 
   */  
  public void setTextView(TextView mTextDialog) {  
    this.mTextDialog = mTextDialog;  
  }  
  public SideBar(Context context, AttributeSet attrs, int defStyle) {  
    super(context, attrs, defStyle);  
  }  
  public SideBar(Context context, AttributeSet attrs) {  
    super(context, attrs);  
  }  
  public SideBar(Context context) {  
    super(context);  
  }  
  /** 
   * 重写这个方法 
   */  
  protected void onDraw(Canvas canvas) {  
    super.onDraw(canvas);  
    // 获取焦点改变背景颜色.  
    int height = getHeight();// 获取对应高度  
    int width = getWidth(); // 获取对应宽度  
    int singleHeight = height / A_Z.length-2;// 获取每一个字母的高度  (这里-2仅仅是为了好看而已)
    for (int i = 0; i < A_Z.length; i++) {  
      paint.setColor(Color.rgb(33, 65, 98));  //设置字体颜色 
      paint.setTypeface(Typeface.DEFAULT_BOLD);  //设置字体
      paint.setAntiAlias(true);  //设置抗锯齿
      paint.setTextSize(30);  //设置字母字体大小
      // 选中的状态  
      if (i == choose) {  
        paint.setColor(Color.parseColor("#3399ff"));  //选中的字母改变颜色
        paint.setFakeBoldText(true);  //设置字体为粗体
      }  
      // x坐标等于中间-字符串宽度的一半.  
      float xPos = width / 2 - paint.measureText(A_Z[i]) / 2;  
      float yPos = singleHeight * i + singleHeight;  
      canvas.drawText(A_Z[i], xPos, yPos, paint);  //绘制所有的字母
      paint.reset();// 重置画笔  
    }  
  }  
  @Override  
  public boolean dispatchTouchEvent(MotionEvent event) {  
    final int action = event.getAction();  
    final float y = event.getY();// 点击y坐标  
    final int oldChoose = choose;  
    final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;  
    final int c = (int) (y / getHeight() * A_Z.length);// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.  
    switch (action) {  
    case MotionEvent.ACTION_UP:  
      setBackgroundDrawable(new ColorDrawable(0x00000000));  
      choose = -1;//  
      invalidate();  
      if (mTextDialog != null) {  
        mTextDialog.setVisibility(View.INVISIBLE);  
      }  
      break;  
    default:  
      setBackgroundResource(R.drawable.sidebar_background);  
      if (oldChoose != c) {  //判断选中字母是否发生改变
        if (c >= 0 && c < A_Z.length) {  
          if (listener != null) {  
            listener.onTouchingLetterChanged(A_Z[c]);  
          }  
          if (mTextDialog != null) {  
            mTextDialog.setText(A_Z[c]);  
            mTextDialog.setVisibility(View.VISIBLE);  
          }  
          choose = c;  
          invalidate();  
        }  
      }  
      break;  
    }  
    return true;  
  }  
  /** 
   * 向外公开的方法 
   *  
   * @param onTouchingLetterChangedListener 
   */  
  public void setOnTouchingLetterChangedListener(  
      OnTouchingLetterChangedListener onTouchingLetterChangedListener) {  
    this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;  
  }  
  /** 
   * 接口 
   *  
   * @author coder 
   *  
   */  
  public interface OnTouchingLetterChangedListener {  
    public void onTouchingLetterChanged(String s);  
  }
}

接下来就是MainActivity和SortAdapter的代码了。

MainActivity.java:

package com.suse.contact;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import com.suse.contact.SideBar.OnTouchingLetterChangedListener;
/**
 * 
* @ClassName: MainActivity 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author 银色的流星 欢迎批评、指导、交流  QQ:962455668
 */
public class MainActivity extends Activity {
  private ListView listView;
  private SortAdapter sortadapter;
  private List<PersonBean> data;
  private SideBar sidebar;
  private TextView dialog;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
  }
  private List<PersonBean> getData(String[] data) {
    List<PersonBean> listarray = new ArrayList<PersonBean>();
    for (int i = 0; i < data.length; i++) {
      String pinyin = PinyinUtils.getPingYin(data[i]);
      String Fpinyin = pinyin.substring(0, 1).toUpperCase();
      PersonBean person = new PersonBean();
      person.setName(data[i]);
      person.setPinYin(pinyin);
      // 正则表达式,判断首字母是否是英文字母
      if (Fpinyin.matches("[A-Z]")) {
        person.setFirstPinYin(Fpinyin);
      } else {
        person.setFirstPinYin("#");
      }
      listarray.add(person);
    }
    return listarray;
  }
  private void init() {
    // TODO Auto-generated method stub
    sidebar = (SideBar) findViewById(R.id.sidebar);
    listView = (ListView) findViewById(R.id.listview);
    dialog = (TextView) findViewById(R.id.dialog);
    sidebar.setTextView(dialog);
    // 设置字母导航触摸监听
    sidebar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
      @Override
      public void onTouchingLetterChanged(String s) {
        // TODO Auto-generated method stub
        // 该字母首次出现的位置
        int position = sortadapter.getPositionForSelection(s.charAt(0));
        if (position != -1) {
          listView.setSelection(position);
        }
      }
    });
    data = getData(getResources().getStringArray(R.array.listpersons));
    // 数据在放在adapter之前需要排序
    Collections.sort(data, new PinyinComparator());
    sortadapter = new SortAdapter(this, data);
    listView.setAdapter(sortadapter);
  }
}

SortAdapter.java:

package com.suse.contact;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SortAdapter extends BaseAdapter {
  private Context context;
  private List<PersonBean> persons;
  private LayoutInflater inflater;
  public SortAdapter(Context context, List<PersonBean> persons) {
    this.context = context;
    this.persons = persons;
    this.inflater = LayoutInflater.from(context);
  }
  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return persons.size();
  }
  @Override
  public Object getItem(int position) {
    // TODO Auto-generated method stub
    return persons.get(position);
  }
  @Override
  public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewholder = null;
    PersonBean person = persons.get(position);
    if (convertView == null) {
      viewholder = new ViewHolder();
      convertView = inflater.inflate(R.layout.list_item, null);
      viewholder.tv_tag = (TextView) convertView
          .findViewById(R.id.tv_lv_item_tag);
      viewholder.tv_name = (TextView) convertView
          .findViewById(R.id.tv_lv_item_name);
      convertView.setTag(viewholder);
    } else {
      viewholder = (ViewHolder) convertView.getTag();
    }
    // 获取首字母的assii值
    int selection = person.getFirstPinYin().charAt(0);
    // 通过首字母的assii值来判断是否显示字母
    int positionForSelection = getPositionForSelection(selection);
    if (position == positionForSelection) {// 相等说明需要显示字母
      viewholder.tv_tag.setVisibility(View.VISIBLE);
      viewholder.tv_tag.setText(person.getFirstPinYin());
    } else {
      viewholder.tv_tag.setVisibility(View.GONE);
    }
    viewholder.tv_name.setText(person.getName());
    return convertView;
  }
  public int getPositionForSelection(int selection) {
    for (int i = 0; i < persons.size(); i++) {
      String Fpinyin = persons.get(i).getFirstPinYin();
      char first = Fpinyin.toUpperCase().charAt(0);
      if (first == selection) {
        return i;
      }
    }
    return -1;
  }
  class ViewHolder {
    TextView tv_tag;
    TextView tv_name;
  }
}

虽然不全,但比较重要的代码都已经贴上去了。

demo下载: http://download.csdn.net/detail/af74776/8997177

其他相关的文章:

http://blog.csdn.net/guolin_blog/article/details/9033553

http://blog.csdn.net/xiaanming/article/details/12684155(这个比我这个好)

http://blog.csdn.net/b275518834/article/details/9327485z

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值