Я столкнулся с проблемой при показе предварительного просмотра первой буквы в списке Android, когда я делаю быстрый прокрутку, я получаю предварительный просмотр текста, но он будет указывать на неправильное расположение в списке.
Например, пожалуйста, взгляните на изображение ниже, в этом теперь мы находимся в разделе M, все еще появляется L-письмо.
Вот код Listadapter, который реализует вышеупомянутый Technic, любую ошибку в коде?
class MyListAdaptor extends ArrayAdapter<String> implements
SectionIndexer
{
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdaptor(Context context, LinkedList<String> items) {
super(context, R.layout.list_item, items);
alphaIndexer = new HashMap<String, Integer>();
int size = items.size();
for (int x = 0; x < size; x++) {
String s = items.get(x);
// get the first letter of the store
String ch = s.substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();
// HashMap will prevent duplicates
alphaIndexer.put(ch, x);
}
Set<String> sectionLetters = alphaIndexer.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<String>(
sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sectionList.toArray(sections);
}
public int getPositionForSection(int section) {
return alphaIndexer.get(sections[section]);
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
return sections;
}
}
Используя alphaIndexer.put(ch, x);
чтобы предотвратить дублирование, вы сохраняете последнюю позицию для элемента, начинающегося с ch
вместо первого. Это связано с тем, что каждый вызов, put
другим, кроме первого с заданным ключом, будет обновлять старое значение. Попробуйте этот код, и вы будете на один шаг ближе:
if( !alphaIndexer.containsKey(ch) )
alphaIndexer.put(ch, x);