How to show alphabetical letters on side of Android ListView

前端 未结 2 849
有刺的猬
有刺的猬 2020-11-30 22:45

I\'ve looked at a lot of tutorials for making a ListView have the alphabetical letters on the side (like the Contacts list), but they all seem to using a ListActivity class

2条回答
  •  温柔的废话
    2020-11-30 23:22

    I forgot to instantiate alphaIndexer. Works perfectly now.

    class AlphabeticalAdapter extends ArrayAdapter implements SectionIndexer
    {
        private HashMap alphaIndexer;
        private String[] sections;
    
        public AlphabeticalAdapter(Context c, int resource, List data)
        {
            super(c, resource, data);
            alphaIndexer = new HashMap();
            for (int i = 0; i < data.size(); i++)
            {
                String s = data.get(i).substring(0, 1).toUpperCase();
                if (!alphaIndexer.containsKey(s))
                    alphaIndexer.put(s, i);
            }
    
            Set sectionLetters = alphaIndexer.keySet();
            ArrayList sectionList = new ArrayList(sectionLetters);
            Collections.sort(sectionList);
            sections = new String[sectionList.size()];
            for (int i = 0; i < sectionList.size(); i++)
                sections[i] = sectionList.get(i);   
        }
    
        public int getPositionForSection(int section)
        {   
            return alphaIndexer.get(sections[section]);
        }
    
        public int getSectionForPosition(int position)
        {
            return 1;
        }
    
        public Object[] getSections()
        {
            return sections;
        }
    }
    

提交回复
热议问题