0.概要
游标ListView,也可以叫索引ListView,提供索引标签,使用户能够快速定位列表项。
效果如图:
1.游标(Fast scroll thumb)
就是右边的那个拖动的方块,这个非常的简单:
<ListView
android:id="@+id/tweaked_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"/>
也可以用在java后台书写:
tweakedListView.setFastScrollEnabled(true);
在数据量有一定大的时候,滑动列表,就会出现右边的所谓的"游标"了。
我们看下源代码,其实就是启用FastScroller对象:
//启用FastScroller对象
public void setFastScrollEnabled(boolean enabled) {
mFastScrollEnabled = enabled;
if (enabled) {
if (mFastScroller == null) {
mFastScroller = new FastScroller(getContext(), this);
}
} else {
if (mFastScroller != null) {
mFastScroller.stop();
mFastScroller = null;
}
}
}
2.字母索引
android系统给提供了一个简单的方法:使用AlphabetIndexer。
AlphabetIndexer,实现了SectionIndexer接口,是adapter的一个辅助类,辅助实现在快滑时,显示索引字母。
使用字母索引的话,必须保证数据列表是按字母顺序排序,以便AlphabetIndexerh采用二分查找法快速定位。
/**
* Cursor表示数据游标
* sortedColumnIndex数据集合中的第几列
* alphabet字母列表,用的最多的是"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
**/
public AlphabetIndexer(Cursor cursor, int sortedColumnIndex, CharSequence alphabet) {
}
用到3个方法:
//这三个方法,实现了索引数据和列表数据的对应和定位
public int getPositionForSection(int section) {
}
public int getSectionForPosition(int position) {
}
public Object[] getSections() {
}
3.游标Cursor的实现
Cursor接口的实现,有两种选择:
(1).直接使用数据库查询返回的cursor
(2).自定义实现Cursor接口的新类
第一种方式很简单,查询一下数据库返回Cursor即可。
这里我们以第二种方式实践,伪装一个Cursor,主要是实现3个方法:
(1).getCount()
(2). moveToPosition()
(3). getString()
/**
* 伪装一个Cursor供AlphabetIndexer作数据索引源
*/
private class IndexCursor implements Cursor{
private ListAdapter adapter;
private int position;
private Map<String, String> map;
public IndexCursor(ListAdapter adapter){
this.adapter = adapter;
}
@Override
public int getCount() {
return this.adapter.getCount();}
/**
* 取得索引字母,这个方法非常重要,根