android - 添加到 RecyclerView 的项目未显示在底部

标签 android android-recyclerview linearlayoutmanager

我有一个 RecyclerView,我用它来以文本应用程序类型的方式显示消息。我的意思是,添加到 RecyclerView 的新消息应该出现在底部。

目前,我在 LinearLayoutManager 上使用 .setStackFromEnd(true) 使消息从底部开始显示:

layMng = new LinearLayoutManager(this);
layMng.setStackFromEnd(true);

mRecyclerView.setLayoutManager(layMng);
mRecyclerView.setAdapter(mAdapter);

发生的情况是,当接收到足够多的消息并且消息列表即将溢出屏幕顶部时,它将停止始终在底部显示新消息。我必须手动向下滚动才能看到新增内容。

我如何让它始终显示最新消息或在收到新项目时让 RecyclerView 向下滚动?

我在我的布局管理器上尝试了各种方法,例如 .scrollToPosition().scrollToPositionWithOffset() 但到目前为止我看到的所有建议都没有奏效。关于这个问题的一些 StackOverflow 热门问题的热门答案甚至无法解决原始问题..

那么这是怎么做到的呢?

最佳答案

请检查layout_height。应该是 android:layout_height="match_parent"

在 UI 线程中运行 smoothScrollToPosition

我的代码中的代码 fragment

            <android.support.v7.widget.RecyclerView
                android:id="@+id/topic_screen_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="18dp"

                />

//这里的 topicScreenList 引用了我的 Recylerview: //-messageAdapter: 引用适配器对象

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    layoutManager.setStackFromEnd(true);
    topicScreenList.setLayoutManager(layoutManager);
    topicScreenList.setAdapter(messageAdapter);
}

收到任何新消息后,后端服务会调用以下代码

-此处 MessageItem 引用适配器使用的新消息项

@Override
public void onNewMessage(final MessageItem messageItem) {
    if (getActivity() != null) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {                  
               messageAdapter.addMessageToEnd(messageItem);

       topicScreenList.smoothScrollToPosition(messageAdapter.getItemCount());

            }
        });
    }
}


//code from my Adapter  
public void addMessageToEnd(MessageItem messageItem) {
    messageItems.add(messageItem);
    notifyItemInserted(messageItems.size() -1);
}

关于android - 添加到 RecyclerView 的项目未显示在底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37982198/

相关文章:

android - 使用 Visual Basic 开发应用程序

android - Lint 警告 : Variable is already assigned to this value

android - 查找 RecyclerView 中第一个可见项目的顶部偏移量

java - 在到达底部后自动滚动到回收器 View 顶部的最佳方法是什么?

android - RecyclerView LinearLayout 管理器在横向模式下总是返回 -1 - findLastCompletelyVisibleItemPosition()

android - RecyclerView 平滑滚动

android - 数据绑定(bind) RecyclerView : Cannot find the setter for attribute 'app:items'

android - GCM 如何处理带有 BroadCastReceiver 的应用程序

java - fragment 中的空回收器 View

android - 在 Recyclerview 适配器上设置 notifyDataSetChanged()