android – notifyItemInserted()在零索引处插入第一个项目时不起作用

前端之家收集整理的这篇文章主要介绍了android – notifyItemInserted()在零索引处插入第一个项目时不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在第一个位置的回收者视图中插入一个项目,即0索引如下
  1. try {
  2. commentList.add(new Comment(
  3. Preferences.getProfileImageUrl(),"",Preferences.getUserName(DONApplication.getInstance()),String.valueOf(Preferences.getUserId(DONApplication.getInstance())),response.getString("comment_id"),commentText
  4. ));
  5. commentAdapter.notifyItemInserted(commentList.size() - 1);
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. }

但它根本没有显示,但当我关闭窗口并再次打开它时,它变得可见.我不知道为什么会这样.有人能帮我吗?

解决方法

经过几个小时 – 这就是我发现的.
项目0已添加到列表中,屏幕已显示之前为0-9的项目,现在显示项目1-10.

您需要以编程方式滚动到位置0,以便查看新添加的项目.

我用了

  1. public void onAttachedToRecyclerView(RecyclerView recyclerView) {
  2. this.recyclerView = recyclerView;
  3. super.onAttachedToRecyclerView(recyclerView);
  4. }

获取对连接到适配器的recyclerView的引用(在我的情况下,我知道只有一个可能的recyclelerView,javadoc声明可能有多个)

在位置0添加项目后,我检查了第一个可见项目是否为0(如果用户已经向下滚动,我不想滚动)

  1. private void restoreScrollPositionAfterAdAdded() {
  2. LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
  3. if (layoutManager != null) {
  4. int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
  5.  
  6. if (firstVisibleItemPosition == 0){
  7. layoutManager.scrollToPosition(0);
  8. }
  9. }
  10. }

猜你在找的Android相关文章