SectionIndexer接口不会更新

时间:2015-01-05 16:18:30

标签: android listview adapter

我想用字母顺序创建一个listview,以便在快速滚动时可以看到映射到每个部分的字母。初始化listview时,以下工作正常。但是,如果列表更改(例如,添加或删除行),则即使每次都创建新适配器,索引器似乎也不会更新。它使用与原始列表相同的字母集。

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

1 个答案:

答案 0 :(得分:0)

  

请参阅此解决方案Code

使用过滤器更新SectionIndexer或任何数据更改都会覆盖此方法。这对我有用。

 @Override
    public void notifyDataSetInvalidated() {
        //write your code 
        super.notifyDataSetInvalidated();
    }