【发布时间】:2018-08-23 16:13:09
【问题描述】:
我正在尝试实现一个带有标题预览的快速滚动列表视图。看起来它几乎可以正常工作,但我遇到了一些奇怪的、类似错误的行为。当我在不使用快速滚动条的情况下向下滚动时,快速滚动条会消失,并且几乎只在最后重新出现。所以似乎有一个差距或类似的东西。
我的 ListView 的 ArrayAdapter 实现了 SectionIndexer 及其方法 getSections()、getPositionForSection(int sectionIndex) 和 getSectionForPosition(int position)。我相信 getPositionForSection 方法会引起麻烦。当我记录 sectionIndex 给出的值并向下滚动列表时,该值超过了实际部分的长度(即 20)。这个值来自 SectionIndexer,而不是我自己。 Android refererence 声明:
如果节的起始位置在适配器边界之外, 该位置必须被剪裁以落在适配器的大小范围内。
但是当我将值裁剪为 0 或 section_size -1 (=19) 时,奇怪的行为不断出现。下面是我的 ListView 的 ArrayAdapter 实现 SectionIndexer。注意:当 AsyncTask 中的数据发生变化时,从适配器外部调用 updateSections 方法。我希望有人知道问题是什么!提前致谢。
public class SoortArrayAdapter extends ArrayAdapter<Soort> implements SectionIndexer {
List<Soort> data;
private HashMap<String, Integer> alphaIndexer;
private ArrayList<String> sections;
public SoortArrayAdapter(@NonNull Context context, int resource, int textViewResourceId, List<Soort> data) {
super(context, resource, textViewResourceId, data);
this.data = data;
sections = new ArrayList<>();
alphaIndexer = new HashMap<String, Integer>();
}
private void updateSections() {
alphaIndexer.clear();
sections = new ArrayList<String>();
for (int i = 0; i < data.size(); i++) {
String s = data.get(i).getNaam().substring(0, 1).toUpperCase();
if (!alphaIndexer.containsKey(s)) {
alphaIndexer.put(s, i);
sections.add(s);
}
}
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(data.get(position).getNaam());
return convertView;
}
@Override
public Object[] getSections() {
return sections.toArray(new String[0]);
}
@Override
public int getPositionForSection(int sectionIndex) {
System.out.println(sectionIndex);
if (sectionIndex >= sections.size()) {
return 0;
}
System.out.println("position for section=" + sections.get(sectionIndex));
return alphaIndexer.get(sections.get(sectionIndex));
}
@Override
public int getSectionForPosition(int position) {
String section = data.get(position).getNaam().substring(0, 1).toUpperCase();
System.out.println("section for position=" + section);
return alphaIndexer.get(section);
}
}
【问题讨论】:
标签: java android listview android-arrayadapter listadapter