Android Firebase聊天当添加新项目时,RecyclerView会自动滚动到底部

时间:2016-11-25 03:49:54

标签: android firebase android-recyclerview firebase-realtime-database firebaseui

我正在使用firebase开发一个Android聊天。

我试图研究这个问题,但我找不到一个好的解决方案。

希望有人可以帮助我。

我的问题我希望RecyclerView在添加新项目时自动滚动。

这是我的代码。

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.chatlayoutchat, container, false);

    Connectivity connectivity=new Connectivity();
    if(connectivity.isConnected(getActivity())) {
        if(getArguments() != null) {
            Firebase.setAndroidContext(this.getActivity());
            String ccustomersid = getArguments().getString("customersid");
            String creferralae = getArguments().getString("referralae");
            String ccustomersname = getArguments().getString("customersname");

            customersid = ccustomersid;
            referralae = creferralae;
            customersname = ccustomersname;

            Firebase.setAndroidContext(this.getActivity());


            editText = (EditText) rootView.findViewById(R.id.editText);

            sendbutton = (Button) rootView.findViewById(R.id.button);
            mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
            RecyclerView.LayoutManager layoutmgr = new LinearLayoutManager(getActivity());
            mRecyclerView.setLayoutManager(layoutmgr);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());

            final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            //linearLayoutManager.setReverseLayout(true);
            linearLayoutManager.setStackFromEnd(true);
            mRecyclerView.setLayoutManager(linearLayoutManager);

            from_user = customersid;
            to_user = referralae;
            LoggedInUser = customersname;


            //Log.v("NODE CREATED:", from_user + " " + to_user);


            ref_chatchildnode1 = firebase_chatnode.child(from_user + " " + to_user);

            //ref_chatchildnode2 = firebase_chatnode.child(to_user + " " + from_user);
            sendbutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    newmsg = editText.getText().toString().trim();
                    ChatModel m = new ChatModel();
                    m.setSender(LoggedInUser);
                    m.setMessage(newmsg);
                    ref_chatchildnode1.push().setValue(m);
                    //ref_chatchildnode2.push().setValue(m);
                    editText.setText("");


                }
            });
            ref_chatchildnode1.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    ChatModel chatmsg = dataSnapshot.getValue(ChatModel.class);
                    chatmsgsList.add(chatmsg);
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });

        }

    }else{
        nointernet();
    }

    showGlobalContextActionBar();

    return rootView;
}

@Override
public void onStart() {
    super.onStart();
    mFirebaseAdapter1 = new FirebaseRecyclerAdapter<ChatModel, ChatMessageViewHolder>(ChatModel.class,
            R.layout.textview,
            ChatMessageViewHolder.class,
            ref_chatchildnode1) {
        @Override
        protected void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatModel m, int i) {



            chatMessageViewHolder.sender.setText(m.getSender());
            chatMessageViewHolder.msg.setText(m.getMessage());

        }
    };
    mRecyclerView.setAdapter(mFirebaseAdapter1);

}

4 个答案:

答案 0 :(得分:20)

请查看step 6 of the Firebase codelab for Android,其中使用AdapterDataObserver

mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
   @Override
   public void onItemRangeInserted(int positionStart, int itemCount) {
       super.onItemRangeInserted(positionStart, itemCount);
       int friendlyMessageCount = mFirebaseAdapter.getItemCount();
       int lastVisiblePosition =
              mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
       // If the recycler view is initially being loaded or the 
       // user is at the bottom of the list, scroll to the bottom 
       // of the list to show the newly added message.
       if (lastVisiblePosition == -1 ||
               (positionStart >= (friendlyMessageCount - 1) &&
                       lastVisiblePosition == (positionStart - 1))) {
           mMessageRecyclerView.scrollToPosition(positionStart);
       }
   }
});

答案 1 :(得分:1)

试试以下代码:

         @Override
            public void onStart() {
                super.onStart();
                mFirebaseAdapter1 = new FirebaseRecyclerAdapter<ChatModel, ChatMessageViewHolder>(ChatModel.class,
                        R.layout.textview,
                        ChatMessageViewHolder.class,
                        ref_chatchildnode1) {
                    @Override
                    protected void populateViewHolder(ChatMessageViewHolder chatMessageViewHolder, ChatModel m, int i) {



                        chatMessageViewHolder.sender.setText(m.getSender());
                        chatMessageViewHolder.msg.setText(m.getMessage());

                    }
                };
                mRecyclerView.setAdapter(mFirebaseAdapter1);

        if (mFirebaseAdapter1 != null) { 
                    mRecyclerView.postDelayed(new Runnable() {
                     @Override
                     public void run() { 
                         mRecyclerView.smoothScrollToPosition(mFirebaseAdapter1.getItemCount() - 1);
                     }
                  }, 5); 
              }
            }

答案 2 :(得分:0)

我知道这是一个旧线程,但这也许会有所帮助。

在添加新消息的地方:

yourRVAdapter.addMessage("New message")
val position = yourRVAdapter.itemCount.minus(1) // itemCount will return the size of RV items 
//Now just call your recyclerView.scrollToPosition(int)
chatRV.scrollToPosition(position)

答案 3 :(得分:0)

adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            
         CommentRv.scrollToPosition(adapter.itemCount.minus(1))
        }
    })