今天刚用到SectionIndexer,记录下来也算是个笔记。
当我们使用侧边快速滑动,比如RecyclerViewFastScroller库,就要自己在adapter中继承SectionIndexer接口才能滑动出效果
一般联系人的侧滑都是用AlphabetIndexer简单实现,这里我自己写的逻辑。
我们来看下这个接口必须继承的三个方法:
abstract Object[] getSections()
abstract int getSectionForPosition(int position)
abstract int getPositionForSection(int sectionIndex)
第一个方法,getSections()返回的是一个Object[]数组,表示右边滑动显示的数组,比如ABCD...
这里的section表示一个组,比如数字所有A字母开头的联系人表示一个section,上面26个字母就是26个section,我是这样写的:
扫描二维码关注公众号,回复:
11412697 查看本文章
private static final String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
@Override
public Object[] getSections() {
String[] sectionArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++) {
sectionArr[i] = "" + sections.charAt(i);
}
return sectionArr;
}
把ABCD..放入一个string数组中返回,这样,你的侧边栏就有这些字母了。
第二个方法,getSectionForPosition(int position)返回int值,返回的值即为上面方法object[]中的数值,比如你返回0,侧边栏就会显示A,返回1,侧边栏就会显示B,以此类推。传入的position就是你手动滑到的位置,比如你滑动到了最后一个,就根据最后一个来返回相应的值,具体返回什么,根据你的逻辑。我是这样写的:
@Override
public int getSectionForPosition(int position) {
if (position >= localUsers.size()) {
position = localUsers.size() - 1;
}
String name = localUsers.get(position).getName();
char c_name = SearchHelper3.TnameToPinyin(name).toUpperCase().charAt(0);
for (int i = 0; i < sections.length(); i++) {
if (c_name == sections.charAt(i))
return i;
}
return 0;
}
我这里的数据源为localUsers,首先,防止position滑出界,所以,如果大于数据源size,就让position为数据源中的最后一个。然后取出名字的第一个大写字符,和section中的ABCD...比较,如果相同,就返回字母所在section中的位置,即右侧会显示的字母。
简单使用就这样,第三个方法没有用到。