android sectionindexer教程?

标签 android listview indexer

如何为带有字符串数组的 ListView 创建分类部分索引器?我看过字母索引器的例子,但它是如何为类别实现的,例如第 1 节、第 2 节、第 3 节……?

最佳答案

根据您的需要将其自定义为适配器并设置为您的 ListView ,仅此而已,取自 here

public class ContactsAdapter extends BaseAdapter implements SectionIndexer {

Context context;
String[] strings;
String[] sections ;
HashMap<String, Integer> alphaIndexer;


public ContactsAdapter(Context context, String[] strings) {
    this.context = context;
    this.strings = strings;
    alphaIndexer = new HashMap<String, Integer>();
    int size = strings.length;

    for (int x = 0; x < size; x++) {
        String s = strings[x];
        String ch = s.substring(0, 1);
        ch = ch.toUpperCase();
        if (!alphaIndexer.containsKey(ch))
            alphaIndexer.put(ch, x);
    }

    Set<String> sectionLetters = alphaIndexer.keySet();
    ArrayList<String> sectionList = new ArrayList<>(sectionLetters);
    Collections.sort(sectionList);
    sections = new String[sectionList.size()];
    sectionList.toArray(sections);

}

@Override
public int getCount() {
    return strings.length;
}

@Override
public Object getItem(int position) {
    return strings[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.main, parent, false);
        holder = new ViewHolder();
        holder.text = (TextView) convertView.findViewById(R.id.tv_contact);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.text.setText(strings[position]);

    return convertView;
}

@Override
public Object[] getSections() {

    return sections;
}

@Override
public int getPositionForSection(int sectionIndex) {
    return alphaIndexer.get(sections[sectionIndex]);
}

@Override
public int getSectionForPosition(int position) {
    return 0;
}

static class ViewHolder {
    TextView text;
}
}

在您的 ListView 中

 ContactsAdapter contactsAdapter = new ContactsAdapter(Registration.this, YOUR_Array;

    listview.setAdapter(contactsAdapter);

    listview.setFastScrollEnabled(true);

关于android sectionindexer教程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6883785/

相关文章:

android - 为什么在SDK 30及更高版本中,运行holder.lockCanvas和holder.unlockCanvasAndPost的后台线程仍然会锁定UI线程?

android onscroll手势检测器

android - SingleInstance Activity 让我感到困惑

android - 关闭在 FrameLayout 内膨胀的 fragment

android - 如何单击 ListView 项并获取电话号码?

java - CustomListview 在 ListView 中显示两次状态

c# - C# 中索引器和属性之间有什么关系?

listview - Flutter/Dart : Handling Dropdown changes within a ListView. 生成器,下拉按钮未更新,

c# - 数组索引器签名返回对象 - 它是否装箱?

c# - 为什么这段代码在集合索引器中有新的