【发布时间】:2016-07-12 16:56:53
【问题描述】:
我想用字母适配器制作一个列表视图,以便在快速滚动时可以看到映射到每个部分的字母。初始化列表视图时,以下内容正常工作。但是,如果列表发生更改(例如添加或删除行),即使每次都创建新的适配器,索引器似乎也不会更新。它使用与原始列表相同的一组字母。
private void GenerateListView (final ArrayList<String> listItems) {
try {
listView = (ListView) findViewById(R.id.listView_browser);
// generate section index adapter
AlphabeticalAdapter adapter = new AlphabeticalAdapter(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
// recall scroll position
if (_currPos < listItems.size())
listView.setVerticalScrollbarPosition(_currPos);
} catch (Exception e) {
e.printStackTrace();
}
}
以下是按字母顺序排列的适配器类。
public class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer
{
private HashMap<String, Integer> alphaIndexer;
private String[] sections;
public AlphabeticalAdapter(Context c, int resource, List<String> data)
{
// create ArrayAdapter<String>
super(c, resource, data);
// generate HashMap
alphaIndexer = new HashMap<>();
// generate index
for (int i = 0; i < data.size(); i++)
{
// convert first letter of each entry to upper case
String s = data.get(i).substring(0, 1).toUpperCase();
// map letter with corresponding index
if (!alphaIndexer.containsKey(s))
alphaIndexer.put(s, i);
}
// assign set view of keys in the HashMap
Set<String> sectionLetters = alphaIndexer.keySet();
// generate list from the set view
ArrayList<String> sectionList = new ArrayList<>(sectionLetters);
// sort list alphabetically
Collections.sort(sectionList);
// define and populate string array with the letters
sections = new String[sectionList.size()];
for (int i = 0; i < sectionList.size(); i++)
sections[i] = sectionList.get(i);
}
【问题讨论】:
-
发布完整的堆栈跟踪(即您究竟在哪里得到该错误)
-
在适配器类末尾设置断点并观察变量时出现错误。抱歉,我似乎在 10 分钟前以某种方式修复了它,但这个问题仍然存在。所以他们似乎没有关系。