【发布时间】:2018-02-28 04:18:42
【问题描述】:
我有一个简单的回收视图,其中包含项目(提示)和底部的加载微调器。
这是项目计数和项目视图类型方法的外观:
@Override
public int getItemViewType(int position) {
if (position == getItemCount() - 1) { // last position
return LOADING_FOOTER_VIEW_TYPE;
}
else {
return TIP_VIEW_TYPE;
}
}
@Override
public int getItemCount() {
return tips.size() + 1; // + 1 for the loading footer
}
基本上,我的所有物品下方都有一个加载微调器。
我像这样创建一次适配器:
public TipsListAdapter(TipsActivity tipsActivity, ArrayList<Tip> tips) {
this.tipsActivity = tipsActivity;
this.tips = tips;
}
然后,一旦我获取了其他项目,我就会像这样调用 add:
public void addTips(List<Tip> tips) {
// hide the loading footer temporarily
isAdding = true;
notifyItemChanged(getItemCount() - 1);
// insert the new items
int insertPos = this.tips.size(); // this will basically give us the position of the loading spinner
this.tips.addAll(tips);
notifyItemRangeInserted(insertPos, tips.size());
// allow the loading footer to be shown again
isAdding = false;
notifyItemChanged(getItemCount() - 1);
}
这里奇怪的是,当我这样做时,滚动位置会转到最底部。似乎它跟随加载微调器。这只发生在第一次添加时(即当只有加载微调器最初显示时)。随后的添加保持正确的滚动位置(插入项目的位置)。
如果我像这样将notifyItemRangeInserted() 更改为notifyItemRangeChanged(),则不会发生这种情况:
public void addTips(List<Tip> tips) {
// hide the loading footer temporarily
isAdding = true;
notifyItemChanged(getItemCount() - 1);
// insert the new items
int insertPos = this.tips.size(); // this will basically give us the position of the loading spinner
this.tips.addAll(tips);
notifyItemRangeChanged(insertPos, tips.size());
// allow the loading footer to be shown again
isAdding = false;
notifyItemChanged(getItemCount() - 1);
}
如果我像这样简单地调用notifyDataSetChanged() 也不会发生这种情况:
public void addTips(List<Tip> tips) {
this.tips.addAll(tips);
notifyDataSetChanged();
}
这是在我的 Activity 中设置适配器的代码:
public void setAdapter(@NonNull ArrayList<Tip> tips) {
if (!tips.isEmpty()) { // won't be empty if restoring state
hideProgressBar();
}
tipsList.setAdapter(new TipsListAdapter(this, tips));
}
public void addTips(List<Tip> tips) {
hideProgressBar();
getAdapter().addTips(tips);
restorePageIfNecessary();
}
private TipsListAdapter getAdapter() {
return (TipsListAdapter) tipsList.getAdapter();
}
注意:
- 我不会在任何地方手动设置滚动位置。
- 我打电话给
setAdapter()onResume() -
addTips()在我从服务器获取项目后被调用
如果您需要我的代码的任何其他部分,请告诉我。
【问题讨论】:
-
请显示您的活动
setAdapter代码 -
或完整的活动代码更好..
-
@SantanuSur 我不想发布我的全部活动,因为有大量不相关的代码。但我添加了我的
setAdapter()和addTips()代码。除了这两个地方,我不碰适配器 -
更新了我的答案,请检查..@Sree
标签: android android-support-library android-recyclerview recyclerview-layout