通过SectionIndexer实现微信通讯录

这里主要参考了使用SectionIndexer实现微信通讯录的效果

在这里做个记录

效果图

通过SectionIndexer实现微信通讯录

页面使用RelativeLayout,主要分为三个部分,match_parent的主listView,右边字母的SideBar,还有就是微信那种点击字母时浮动的一个TextView

布局:

  fragment_contacts.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@android:color/transparent"
android:id="@+id/listFragmentContacts"/>
<TextView
android:id="@+id/textFragmentContacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="20dp"
android:textSize="40sp"
android:textColor="@android:color/white"
android:background="#33000000"
android:visibility="gone"
tools:visibility="visible"
tools:text="A"/>
<lee.example.com.testdj.customWeight.ContactsMySideBar
android:id="@+id/sideBarFragmentContacts"
android:layout_width="24dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"/>
</RelativeLayout>

  layout_contacts_item.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!--section,表示组-->
<TextView
android:id="@+id/tvSectionContactsItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:textSize="22sp"
android:textColor="#666666"
tools:text="section"/> <TextView
android:id="@+id/tvNormalContactsItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:textColor="@android:color/black"
android:background="@android:color/white"
android:textSize="20sp"
tools:text="text"/>
</LinearLayout>

实现:

首先,自定义View来实现SideBar,ContactsMySideBar.java

 public class ContactsMySideBar extends View{

     private static final String TAG = "ContactsMySideBar";

     private SectionIndexer sectionIndexer;
private final char[] letters = new char[]{'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 Paint paint; //画笔用来绘制字母
private ListView listView;
private int focusedIndex = -1; //点击选中的索引
private int drawWidth, drawHeight; //绘制单个字母的宽高 public interface OnTouchChangedListener{
void onTouchDown(char c);
void onTouchUp();
} private OnTouchChangedListener listener; public void setOnTouchChangedListener(OnTouchChangedListener listener){
this.listener = listener;
} public void setListView(ListView listView){
this.listView = listView;
sectionIndexer = (SectionIndexer) listView.getAdapter();
} public ContactsMySideBar(Context context) {
super(context);
init();
} public ContactsMySideBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
} public ContactsMySideBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
} private void init(){
//设置画笔属性
paint = new Paint();
paint.setColor(Color.GRAY);
paint.setTextSize(18f);
paint.setTextAlign(Paint.Align.CENTER);
} @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
drawWidth = getMeasuredWidth()/2; //宽度为sideBar的一半
drawHeight = getMeasuredHeight()/letters.length; //设置高度
} @Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < letters.length; i++){
canvas.drawText(String.valueOf(letters[i]), drawWidth, drawHeight + (i * drawHeight), paint);
}
} @Override
public boolean onTouchEvent(MotionEvent event) {
int pointerY = (int) event.getY();
int selectedIndex = pointerY / drawHeight;
if (selectedIndex >= letters.length){
selectedIndex = letters.length - 1;
}else if(selectedIndex < 0){
selectedIndex = 0;
} switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
//点击时设置为半透明
setBackgroundColor(Color.parseColor("#33000000"));
case MotionEvent.ACTION_MOVE:
if (sectionIndexer == null){
sectionIndexer = (SectionIndexer) listView.getAdapter();
}
// Log.d(TAG, letters[selectedIndex] + "");
//根据数组中的元素获取对应的组位置
int position = sectionIndexer.getPositionForSection(letters[selectedIndex]);
Log.d(TAG, "" + position);
if (position == -1){
return true;
}
if (selectedIndex != 0){
if (position != 0){
//改变当前listView所处位置
listView.setSelection(position);
}
}else {
listView.setSelection(position);
} //重绘SideBar
invalidate();
if (null != listener){
listener.onTouchDown(letters[selectedIndex]);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
//松开手指取消背景色
setBackgroundResource(android.R.color.transparent);
invalidate();
if (null != listener){
listener.onTouchUp();
}
break;
}
return true;
}
}

这部分代码很简单,重写了OnMeasure和OnDraw来绘制SideBar,在OnTouchEvent中写出了SideBar的响应事件

定义listView的adapter

SideBarAdapter.java
 public class SideBarAdapter extends BaseAdapter implements SectionIndexer{

     private static final String TAG = "SideBarAdapter";

     private Context context;
private List<ContactsModel> modelList;
private LayoutInflater layoutInflater; public SideBarAdapter(Context context, List<ContactsModel> modelList){
this.context = context;
this.modelList = modelList;
layoutInflater = LayoutInflater.from(context);
} @Override
public int getCount() {
return modelList.size();
} @Override
public ContactsModel getItem(int i) {
return modelList.get(i);
} @Override
public long getItemId(int i) {
return i;
} @Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
Holder holder;
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.layout_contacts_item, viewGroup, false);
holder = new Holder();
holder.normalTv = (TextView) convertView.findViewById(R.id.tvNormalContactsItem);
holder.sectionTv = (TextView) convertView.findViewById(R.id.tvSectionContactsItem);
convertView.setTag(holder);
}else {
holder = (Holder) convertView.getTag();
}
String text = modelList.get(i).getName();
setSectionTv(i, holder, text);
setNormalTv(holder, text); return convertView;
} private void setNormalTv(Holder holder, String text){
holder.normalTv.setText(text);
} private void setSectionTv(int position, Holder holder, String text){
//获取每个item字符串的头一个字符
// Log.d(TAG, ZhCharactersUtil.changeToSpell(text));
char firstChar = ZhCharactersUtil.changeToSpell(text).toUpperCase().charAt(0);
//若为第一个位置直接设置组view就行
if (position == 0) {
holder.sectionTv.setVisibility(View.VISIBLE);
holder.sectionTv.setText((firstChar + "").toUpperCase());
}
//若不是,需判断当前item首字母与上一个item首字母是否一致,再设置组view
else {
String preLabel = modelList.get(position - 1).getName();
//获取上一个item的首字母
char preFirstChar = ZhCharactersUtil.changeToSpell(preLabel).toUpperCase().charAt(0);
if (firstChar != preFirstChar) {
holder.sectionTv.setVisibility(View.VISIBLE);
holder.sectionTv.setText((firstChar + "").toUpperCase());
} else {
//若与上一个item首字母一致则不需要重复设置组view
holder.sectionTv.setVisibility(View.GONE);
}
}
} @Override
public Object[] getSections() {
//获取组信息的数组,比如这里可以返回char[]{'A','B',...}
return new Object[0];
} @Override
public int getPositionForSection(int section) {
//根据组信息获取索引
for (int i = 0; i < modelList.size(); i++) {
String str = modelList.get(i).getName();
char firstChar = ZhCharactersUtil.changeToSpell(str).toUpperCase().charAt(0);
if (firstChar == section) {
return i;
}
}
return 0;
} @Override
public int getSectionForPosition(int i) {
//根据索引获取组信息,这里不做处理
return 0;
} private final class Holder {
TextView normalTv, sectionTv;
}
}

这里用到了一个第三方,jpinyin,是用来对汉字进行处理,转换成拼音等等,ZhCharactersUtil.java就是用来处理汉字的,我这里只需要取拼音的第一个字母

 public class ZhCharactersUtil {
public static String changeToSpell(String string){
char[] chars = PinyinHelper.getShortPinyin(string).toCharArray();
return chars[0] + "";
} }

这里的ContactsModel里边只有两个属性,一个name,一个firstCharacter,其中firstCharacter是用来进行排序的,上边adapter的代码可以用modelList.get(i).getFirstCharacter()来简化一些,偷懒了,所以开始写好了就放在那没动,这里这个model就不记录了。

在Activity中使用,我这里是在fragment中使用,都是一样的

 private ListView listView;
//悬浮的textView
private TextView maskText;
private ContactsMySideBar sideBar; //然后对他们进行初始化
 private void initData(){
ContactsModel model1 = new ContactsModel("张一");
ContactsModel model2 = new ContactsModel("张二");
ContactsModel model3 = new ContactsModel("李一");
ContactsModel model4 = new ContactsModel("李二");
ContactsModel model5 = new ContactsModel("赵一");
ContactsModel model6 = new ContactsModel("赵二");
ContactsModel model7 = new ContactsModel("王三");
ContactsModel model8 = new ContactsModel("王二");
ContactsModel model9 = new ContactsModel("阿张");
ContactsModel model10 = new ContactsModel("不行");
ContactsModel model11 = new ContactsModel("特别");
ContactsModel model12 = new ContactsModel("将就");
ContactsModel model13 = new ContactsModel("公司");
ContactsModel model14 = new ContactsModel("空是");
ContactsModel model15 = new ContactsModel("好附件打开");
ContactsModel model16 = new ContactsModel("现在");
ContactsModel model17 = new ContactsModel("哦跑"); ContactsModel model18 = new ContactsModel("aaasss");
ContactsModel model19 = new ContactsModel("bbb");
ContactsModel model20 = new ContactsModel("s");
ContactsModel model21 = new ContactsModel("jjj");
ContactsModel model22 = new ContactsModel("oot"); modelList.add(model1);
modelList.add(model2);
modelList.add(model3);
modelList.add(model4);
modelList.add(model5);
modelList.add(model6);
modelList.add(model7);
modelList.add(model8);
modelList.add(model9);
modelList.add(model10);
modelList.add(model11);
modelList.add(model12);
modelList.add(model13);
modelList.add(model14);
modelList.add(model15);
modelList.add(model16);
modelList.add(model17);
// modelList.add(model18);
// modelList.add(model19);
// modelList.add(model20);
// modelList.add(model21);
// modelList.add(model22);
Collections.sort(modelList, new Comparator<ContactsModel>() {
@Override
public int compare(ContactsModel contactsModel, ContactsModel t1) {
return contactsModel.getFirstCharacter().compareTo(t1.getFirstCharacter());
}
}); adapter = new SideBarAdapter(getContext(), modelList);
listView.setAdapter(adapter);
sideBar.setListView(listView);
sideBar.setOnTouchChangedListener(new ContactsMySideBar.OnTouchChangedListener() {
@Override
public void onTouchDown(char c) {
maskText.setText(c + "");
maskText.setVisibility(View.VISIBLE);
} @Override
public void onTouchUp() {
maskText.setVisibility(View.GONE);
}
});
}

这里添加了一些假数据,完成。

上一篇:九度OJ 1010:计算A+B【字符串和数组】


下一篇:vim在选中的几行中查找并替换