gradle
项目下app的build.gradle中依赖:
compile 'me.yokeyword:indexablerecyclerview:1.3.0'
compile 'com.android.support:appcompat-v7:你使用的版本号'
compile 'com.android.support:recyclerview-v7:你使用的版本号'
Xml
<me.yokeyword.indexablerv.IndexableLayout
...
app:indexBar_layout_width="24dp" // IndexBar:width
app:indexBar_background="#08000000" // IndexBar:background
app:indexBar_textColor="#000000" // IndexBar:textColor
app:indexBar_selectedTextColor="#f33737" // IndexBar:isSelected textColor
app:indexBar_textSize="14sp" // IndexBar:textSize
app:indexBar_textSpace="6dp" /> // IndexBar:text lineSpace
3步集成
1、实体类实现IndexableEntity
public class CityEntity implements IndexableEntity {
...
private String name;
private String pinyin;
@Override
public String getFieldIndexBy() {
return name; // return 你需要根据该属性排序的field
}
@Override
public void setFieldIndexBy(String indexByField) {
this.name = indexByField; // 同上
}
@Override
public void setFieldPinyinIndexBy(String pinyin) {
this.pinyin = pinyin; // 保存排序field的拼音,在执行比如搜索等功能时有用 (若不需要,空实现该方法即可)
}
}
2、继承IndexAdapter
public class CityAdapter extends IndexableAdapter<CityEntity> {
private LayoutInflater mInflater;
public CityAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateTitleViewHolder(ViewGroup parent) {
View view = mInflater.inflate(R.layout.recycler_view_item_city_title, parent, false);
return new IndexVH(view);
}
@Override
public RecyclerView.ViewHolder onCreateContentViewHolder(ViewGroup parent) {
View view = mInflater.inflate(R.layout.recycler_view_item_city, parent, false);
return new ContentVH(view);
}
@Override
public void onBindTitleViewHolder(RecyclerView.ViewHolder holder, String indexTitle) {
IndexVH vh = (IndexVH) holder;
vh.tv.setText(indexTitle);
}
@Override
public void onBindContentViewHolder(RecyclerView.ViewHolder holder, CityEntity entity) {
ContentVH vh = (ContentVH) holder;
vh.tv.setText(entity.getFieldIndexBy());
}
private class IndexVH extends RecyclerView.ViewHolder {
TextView tv;
public IndexVH(View itemView) {
super(itemView);
tv = (TextView) itemView.findViewById(R.id.tv_item);
}
}
private class ContentVH extends RecyclerView.ViewHolder {
TextView tv;
public ContentVH(View itemView) {
super(itemView);
tv = (TextView) itemView.findViewById(R.id.tv_name);
}
}
3、绑定视图和数据
// 支持LinearLayoutManager, GridLayoutManager
indexableLayout.setLayoutManager(LayoutManager);
CityAdapter adapter = new CityAdapter(this);
indexableLayout.setAdapter(adapter);
// 排序过程是异步的 另有setDatas(mDatas,IndexCallback callback) // callback在datas异步排序结束后回调
adapter.setDatas(mDatas);
// 另有setOnItemTitleClickListener(listener),点击TitleItem点击事件以及LongClick
adapter.setOnItemContentClickListener(listener);