Android SectionIndexer 教程

3

如何为具有字符串数组的listview创建一个分类部分索引?我已经看到了字母索引器的例子,但是如何实现类别(例如Section 1、Section 2、Section 3)呢?


我正在这里做类似的事情 https://dev59.com/xeo6XIcBkEYKwwoYQiO7 - Etienne Lawlor
请查看此链接:http://androidcustomviews.com/portfolio-category/custom-views/ - Girish Bhutiya
1个回答

4

根据您的需求自定义此适配器并设置到您的列表视图中,就是这样,参考这里

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;
}
}

在您的列表视图中

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

    listview.setAdapter(contactsAdapter);

    listview.setFastScrollEnabled(true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接