我看了很多有关制作ListView侧边字母表(如联系人列表)的教程,但它们似乎都使用ListActivity类和/或来自数据库的数据,而我只是使用ListView(没有特殊活动)和一个数据ArrayList。 有人知道我如何在我的ListView中实现那个联系人列表的字母滚动功能吗?
编辑后
我按照 这个教程 做,本以为最终可以解决问题,但还是出现了强制关闭。
在LogCat中,它显示
编辑:如果您想要在滚动时使您的滚动条出现在正确的位置,则getSectionForPosition非常重要。仅返回1(或0)表示您只是在第一(或第二)部分中滚动,这将导致滚动条的错误位置(大多数情况下超出屏幕)。添加的代码返回适当的部分,因此滚动条可以知道它实际上在哪里。
编辑后
我按照 这个教程 做,本以为最终可以解决问题,但还是出现了强制关闭。
class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer
{
private HashMap<String, Integer> alphaIndexer;
private String[] sections;
public AlphabeticalAdapter(Context c, int resource, List<String> data)
{
super(c, resource, data);
for (int i = 0; i < data.size(); i++)
{
String s = data.get(i).substring(0, 1).toUpperCase();
alphaIndexer.put(s, i);
}
Set<String> sectionLetters = alphaIndexer.keySet();
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 1;
}
public Object[] getSections()
{
return sections;
}
}
在LogCat中,它显示
java.lang.RuntimeException: Unable to resume activity {(我制作的另一个应用程序包名) android.app.SuperNotCalledExcpetion
。我认为这非常奇怪,因为我在我正在处理的应用程序中根本没有引用那个其他应用程序。我尝试卸载那个其他应用程序,仍然出现了强制关闭,但是我可以看到LogCat说了什么,因为它没有更新。
最终编辑
这是可工作的代码。很抱歉发布晚了大约9个月。
class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer
{
private HashMap<String, Integer> alphaIndexer;
private String[] sections;
public AlphabeticalAdapter(Context c, int resource, List<String> data)
{
super(c, resource, data);
alphaIndexer = new HashMap<String, Integer>();
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<String> sectionLetters = alphaIndexer.keySet();
ArrayList<String> sectionList = new ArrayList<String>(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)
{
for ( int i = sections.length - 1; i >= 0; i-- ) {
if ( position >= alphaIndexer.get( sections[ i ] ) ) {
return i;
}
}
return 0;
}
public Object[] getSections()
{
return sections;
}
}
编辑:如果您想要在滚动时使您的滚动条出现在正确的位置,则getSectionForPosition非常重要。仅返回1(或0)表示您只是在第一(或第二)部分中滚动,这将导致滚动条的错误位置(大多数情况下超出屏幕)。添加的代码返回适当的部分,因此滚动条可以知道它实际上在哪里。