先看效果图
整体思路分为两部分,左边的listView和右边的侧滑菜单,
侧滑菜单实现和listView的联动的效果
listView的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="wrap_content" android:orientation="vertical">
<TextView android:id="@+id/show_letter" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textColor="@color/colorPrimary" android:textSize="20sp" />
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<ImageView android:id="@+id/userface" android:layout_width="72dp" android:layout_height="72dp" android:padding="12dp" android:src="@mipmap/ic_launcher" />
<TextView android:id="@+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="36dp" android:layout_toRightOf="@id/userface" android:gravity="center" android:text="username" />
<TextView android:id="@+id/usernum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="36dp" android:layout_toRightOf="@id/username" android:gravity="center" android:text="username" />
</RelativeLayout>
</LinearLayout>
public class MyAdapter extends BaseAdapter implements SectionIndexer {
private List<Person> dataList;
private Context context;
public MyAdapter(Context context, List<Person> list) {
this.context = context;
this.dataList = list;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.layout_item, null);
holder = new ViewHolder();
holder.showLetter = (TextView) convertView.findViewById(R.id.show_letter);
holder.username = (TextView) convertView.findViewById(R.id.username);
holder.usernum= (TextView) convertView.findViewById(R.id.usernum);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Person person = dataList.get(position);
holder.username.setText(person.getUsername());
holder.usernum.setText(person.getNum());
//获得当前position是属于哪个分组,同时返回对应的字母
int sectionForPosition = getSectionForPosition(position);
//获得该分组对应字母第一个的position,
int positionForSection = getPositionForSection(sectionForPosition);
//查看当前position是不是当前item所在分组的第一个item
//如果是,则显示showLetter,否则隐藏
if (position == positionForSection) {
holder.showLetter.setVisibility(View.VISIBLE);
holder.showLetter.setText(person.getFirstLetter()+"");
} else {
holder.showLetter.setVisibility(View.GONE);
}
return convertView;
}
//传入一个分组值[A....Z],获得该分组的第一项的position
//通过该项的位置,获得所在分类组的索引号
public int getPositionForSection(int sectionIndex) {
for (int i = 0; i < dataList.size(); i++) {
if (dataList.get(i).getFirstLetter() == sectionIndex) {
return i;
}
}
return -1;
}
//传入一个position,获得该position所在的分组
//根据分类列的索引号获得该序列的首个位置
public int getSectionForPosition(int position) {
return dataList.get(position).getFirstLetter();
}
class ViewHolder {
TextView username, showLetter,usernum;
}
public Object[] getSections() {
return new Object[0];
}
}
public class SlideBar extends View {
//当前手指滑动到的位置
private int choosedPosition = -1;
//画文字的画笔
private Paint paint;
//右边的所有文字
private String[] letters = new String[]{"#", "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"};
//页面正中央的TextView,用来显示手指当前滑动到的位置的文本
private TextView textViewDialog;
//接口变量,该接口主要用来实现当手指在右边的滑动控件上滑动时ListView能够跟着滚动
private UpdateListView updateListView;
public SlideBar(Context context) {
this(context, null);
}
public SlideBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlideBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
//设置抗锯齿
paint.setAntiAlias(true);
//设置画笔的文字大小
paint.setTextSize(40);
}
public void setTextViewDialog(TextView textViewDialog) {
this.textViewDialog = textViewDialog;
}
@Override
protected void onDraw(Canvas canvas) {
//每一个侧滑栏字母的高度
int perTextHeight = getHeight() / letters.length;
for (int i = 0; i < letters.length; i++) {
//如果当前字母被选中,那么久将其颜色改变为红色
if (i == choosedPosition) {
paint.setColor(Color.RED);
} else {
paint.setColor(Color.BLACK);
}
//开始将侧滑栏字母绘制在上面
canvas.drawText(letters[i], (getWidth() - paint.measureText(letters[i])) / 2, (i + 1) * perTextHeight, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//通过获取当前的滑动事件的y坐标,计算当前手指在那个字母上面
int perTextHeight = getHeight() / letters.length;
float y = event.getY();
int currentPosition = (int) (y / perTextHeight);
String letter = letters[currentPosition];
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
//当手指停止滑动,离开时,将自定义控件的背景的阴影效果取消显示,设置为透明的颜色
setBackgroundColor(Color.TRANSPARENT);
if (textViewDialog != null) {
textViewDialog.setVisibility(View.GONE);
}
break;
default:
//当手指在自定义控件上的时候,就将背景颜色设置为当前颜色,就是浅灰色
setBackgroundColor(Color.parseColor("#cccccc"));
if (currentPosition > -1 && currentPosition < letters.length) {
if (textViewDialog != null) {
textViewDialog.setVisibility(View.VISIBLE);
textViewDialog.setText(letter);
}
if (updateListView != null) {
updateListView.updateListView(letter);
}
choosedPosition = currentPosition;
}
break;
}
//更新我们自定义控件的UI显示
invalidate();
return true;
}
public void setUpdateListView(UpdateListView updateListView) {
this.updateListView = updateListView;
}
//通过接口的回调,实现我们在主代码中的listView一起联动
public interface UpdateListView {
public void updateListView(String currentChar);
}
public void updateSlideBar(int currentChar) {
for (int i = 0; i < letters.length; i++) {
if (currentChar == letters[i].charAt(0)) {
choosedPosition = i;
//更新我们自定义控件的UI显示
invalidate();
break;
}
}
}
}
<?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" android:orientation="horizontal" tools:context="com.lingzhuo.testslidebar01.MainActivity">
<ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" />
<com.lingzhuo.testslidebar01.view.SlideBar android:id="@+id/slideBar" android:layout_width="20dp" android:layout_height="match_parent" android:layout_alignParentRight="true" />
<TextView android:id="@+id/show_letter_in_center" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerInParent="true" android:gravity="center" android:textSize="60sp" android:background="@color/colorGray" android:visibility="gone" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private ListView listView;
private MyAdapter adapter;
private List<Person> dataList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getContacts();
for (Person person : dataList) {
Log.d("MainActivity", person.getUsername() + person.getFirstLetter() + "");
}
adapter=new MyAdapter(getApplicationContext(),dataList);
listView.setAdapter(adapter);
//设置侧滑菜单的一系列参数,以及设置监听事件
initSlideBar();
}
private void initSlideBar() {
//主布局文件中的那个侧滑菜单被滑动才显示的TextView
TextView textView = (TextView) findViewById(R.id.show_letter_in_center);
final SlideBar slideBar = (SlideBar) findViewById(R.id.slideBar);
slideBar.setTextViewDialog(textView);
slideBar.setUpdateListView(new SlideBar.UpdateListView() {
@Override
public void updateListView(String currentChar) {
int positionForSection = adapter.getPositionForSection(currentChar.charAt(0));
listView.setSelection(positionForSection);
}
});
//设置listView滑动的时候,同时更新侧滑索引菜单的显示
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int sectionForPosition = adapter.getSectionForPosition(firstVisibleItem);
slideBar.updateSlideBar(sectionForPosition);
}
});
}
private void init() {
listView = (ListView) findViewById(R.id.listView);
dataList = new ArrayList<>();
}
public void getContacts() {
//通过内容提供器,获取联系人的信息
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
List<Person> dataTemp = new ArrayList<>();
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String num = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//导入的第三方的工具包,用于将汉子转为拼音
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(name.charAt(0));
Person person;
if (pinyin != null) {
person = new Person(name, pinyin[0].toUpperCase().charAt(0), num);
} else {
person = new Person(name, '#' , num);
}
dataTemp.add(person);
}
//对联系人的list数据进行排序,按字母顺序排序
for (int i = 35; i <= 90; i++) {
for (Person person : dataTemp) {
if (person.getFirstLetter() == ((char) i)) {
dataList.add(person);
}
}
}
}
}