Sap*_*rma 8 android insert-update android-recyclerview
我试图在第一个位置的回收者视图中插入一个项目,即0索引如下
try {
commentList.add(new Comment(
Preferences.getProfileImageUrl(),
"",
Preferences.getUserName(DONApplication.getInstance()),
String.valueOf(Preferences.getUserId(DONApplication.getInstance())),
response.getString("comment_id"),
commentText
));
commentAdapter.notifyItemInserted(commentList.size() - 1);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但它根本没有显示,但当我关闭窗口并再次打开它时,它变得可见.我不知道为什么会这样.有人能帮我吗?
Noa*_*ach 12
经过几个小时 - 这就是我发现的.项目0已添加到列表中,并且屏幕已显示之前为0-9的项目,现在显示项目1-10.
您需要以编程方式滚动到位置0,以便查看新添加的项目.
我用了
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
super.onAttachedToRecyclerView(recyclerView);
}
Run Code Online (Sandbox Code Playgroud)
获取对连接到适配器的recyclerView的引用(在我的情况下,我知道只有一个可能的recyclelerView,javadoc声明可能有多个)
在位置0添加项目后,我检查了第一个可见项目是否为0(如果用户已经向下滚动,我不想滚动)
private void restoreScrollPositionAfterAdAdded() {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null) {
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (firstVisibleItemPosition == 0){
layoutManager.scrollToPosition(0);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3932 次 |
| 最近记录: |