我试图在第一个位置的回收者视图中插入一个项目,即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();
- }
解决方法
经过几个小时 – 这就是我发现的.
项目0已添加到列表中,屏幕已显示之前为0-9的项目,现在显示项目1-10.
项目0已添加到列表中,屏幕已显示之前为0-9的项目,现在显示项目1-10.
您需要以编程方式滚动到位置0,以便查看新添加的项目.
我用了
- public void onAttachedToRecyclerView(RecyclerView recyclerView) {
- this.recyclerView = recyclerView;
- super.onAttachedToRecyclerView(recyclerView);
- }
获取对连接到适配器的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);
- }
- }
- }