如何在FireBaseRecycler中将传入消息与传出消息分开

时间:2019-02-23 19:08:13

标签: android firebase firebase-realtime-database

我正在构建此聊天应用。但是我被困在这一点上。我已经为回收站视图创建了布局和视图持有人,并且我正在使用FireBaseRecycler。但是,如何将传入消息与传出消息分开?如何将传入消息推到右侧,将传出消息推到左侧。

这是我的布局代码。回收商夸大了布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:maxWidth="300dp"
        android:minWidth="130dp"
        android:adjustViewBounds="true"


        android:background="@drawable/rounded_corner_out"
        android:orientation="vertical"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="50dp"
        android:layout_marginTop="10dp"
        android:paddingTop="3dp"
        android:paddingStart="3dp"
        android:paddingEnd="16dp"
        android:id="@+id/layout_out"
        android:paddingBottom="2dp">

        <TextView
            android:id="@+id/message_user_out"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:padding="5dp"
            android:text=" "
            android:textSize="1dp"
            android:textColor="#000" />

        <TextView
            android:id="@+id/message_text_out"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="5dp"
            android:layout_marginEnd="0dp"

            android:text="hello darling how are you? How is work? hello darling how are you? How is work? hhhhhjjjjjjjjjjjjjjjjjj"
            android:textColor="#fff" />

        <TextView
            android:id="@+id/message_time_out"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxWidth="100dp"
            android:layout_gravity="bottom|end"
            android:layout_marginTop="-10dp"
            android:layout_marginBottom="5dp"
            android:padding="5dp"
            android:text="22:30:33"
            android:textColor="#fff" />

    </LinearLayout>


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:maxWidth="300dp"
        android:minWidth="130dp"
        android:adjustViewBounds="true"
        android:layout_below="@id/layout_out"
        android:background="@drawable/rounded_corner_in"
        android:orientation="vertical"
        android:layout_marginStart="50dp"
        android:layout_marginEnd="15dp"
        android:layout_marginTop="10dp"
        android:paddingTop="3dp"
        android:paddingStart="3dp"
        android:paddingEnd="16dp"
        android:id="@+id/layout_in"
        android:paddingBottom="2dp">

        <TextView
            android:id="@+id/message_user_in"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:padding="5dp"
            android:text=" "
            android:textSize="1dp"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/message_text_in"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="5dp"
            android:layout_marginEnd="0dp"

            android:text="hello darling how are you? How is work? hello darling how are you? How is work? hhhhhjjjjjjjjjjjjjjjjjj"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/message_time_in"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxWidth="100dp"
            android:layout_gravity="bottom|end"
            android:layout_marginTop="-10dp"
            android:layout_marginBottom="5dp"
            android:padding="5dp"
            android:text="22:30:33"
            android:textColor="@color/colorPrimary" />

    </LinearLayout>







</RelativeLayout>

这是我的模型,它的类名为'ChatMessage'

package com.example.stupidgeek.bboo;

import java.util.Date;

/**
 * Created by STUPID GEEK on 2/18/2019.
 */

public class ChatMessage {

    private String id;
    private String text;
    private long messageTime;
    private boolean messageTypeIn;


    public ChatMessage(String id, String text) {
        this.text = text;
        this.id = id;

        // Initialize to current time
        messageTime = new Date().getTime();
    }

    public ChatMessage(){

    }

    public String getMessageText() {
        return text;
    }

    public void setMessageText(String text) {
        this.text = text;
    }

    public String getMessageUser() {
        return id;
    }

    public void setMessageUser(String id) {
        this.id = id;
    }

    public long getMessageTime() {
        return messageTime;
    }

    public void setMessageTime(long messageTime) {
        this.messageTime = messageTime;
    }

    public  void setMessageTypeIn(boolean messageType)
    {
        this.messageTypeIn = messageType;

    }

    public boolean getMessageTypeIn()
    {
        return messageTypeIn;
    }

}

这是我的聊天窗口,显示聊天的活动

package com.example.stupidgeek.bboo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.List;

public class ChatWindow extends AppCompatActivity {
    private FirebaseRecyclerAdapter<ChatMessage, ChatHolder> adapter;
    // private FirebaseRecyclerAdapter<ChatMessage, ChatHolderIn> adapterIn;

    ChatMessage model;
    RecyclerView list_of_messages;
    private boolean messageType = true;

    private Context mCtx;

    private List<ChatMessage> chatList;
    EditText input;
    FirebaseRecyclerOptions<ChatMessage> options;
    FirebaseRecyclerOptions<ChatMessage> optionsIn;
    int MessageState;
    SnapshotParser<ChatMessage>snapshotParser;
    String UserID;
    String Text;


    //getting the context and product list with constructor


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent goBack = new Intent(this, Main2Activity.class);
        startActivity(goBack);
    }






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_window);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        input = (EditText) findViewById(R.id.input);
        list_of_messages = (RecyclerView) findViewById(R.id.list_of_chat_items);

        FloatingActionButton fab =
                (FloatingActionButton) findViewById(R.id.fab);

        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                final FloatingActionButton fab =
                        (FloatingActionButton) findViewById(R.id.fab);

                // Toast.makeText(getApplicationContext(), "KeyboardDown", Toast.LENGTH_SHORT).show();

                fab.setEnabled(true);
                fab.setImageResource(R.drawable.ic_action_send);
                // Toast.makeText(getApplicationContext(), " Not Empty", Toast.LENGTH_SHORT).show();

                final String textInput = input.getText().toString();
                if ((textInput.length() == 0) || (textInput.length() < 0)) {

                    fab.setEnabled(false);
                    fab.setImageResource(R.drawable.ic_action_send_gray);
                    //  Toast.makeText(getApplicationContext(), "Empty", Toast.LENGTH_SHORT).show();


                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                final FloatingActionButton fab =
                        (FloatingActionButton) findViewById(R.id.fab);

                // TODO Auto-generated method stub
                // Toast.makeText(getApplicationContext(), "KeyboardDown", Toast.LENGTH_SHORT).show();
                fab.setEnabled(true);
                fab.setImageResource(R.drawable.ic_action_send);
                // Toast.makeText(getApplicationContext(), " Not Empty", Toast.LENGTH_SHORT).show();

                final String textInput = input.getText().toString();
                if ((textInput.length() == 0) || (textInput.length() < 0)) {

                    fab.setEnabled(false);
                    fab.setImageResource(R.drawable.ic_action_send_gray);
                    // Toast.makeText(getApplicationContext(), "Empty", Toast.LENGTH_SHORT).show();


                }


            }
        });


        String textInput = input.getText().toString();
        if ((textInput.length() == 0) || (textInput.length() < 0)) {

            fab.setEnabled(false);
            fab.setImageResource(R.drawable.ic_action_send_gray);
            //  Toast.makeText(getApplicationContext(), "Empty", Toast.LENGTH_SHORT).show();


        } else {
            fab.setEnabled(true);
            fab.setImageResource(R.drawable.ic_action_send);
            // Toast.makeText(getApplicationContext(), " Not Empty", Toast.LENGTH_SHORT).show();


        }


        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                // Read the input field and push a new instance
                // of ChatMessage to the Firebase database
                FirebaseDatabase.getInstance()
                        .getReference().child("ebube")
                        .push()
                        .setValue(new ChatMessage(
                                FirebaseAuth.getInstance()
                                        .getCurrentUser()
                                        .getPhoneNumber(), input.getText().toString())
                        );

                // Clear the input

                input.setText("");


            }
        });


        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("ebube").orderByKey();




        if (user == null) {


//put intent to go to mainActivity

            Intent y = new Intent(ChatWindow.this, SignUpActivity.class);
            startActivity(y);

        } else {
            ///
            // User is already signed in. Therefore, display
            // a welcome Toast
            Toast.makeText(this,
                    "Welcome " + FirebaseAuth.getInstance()
                            .getCurrentUser()
                            .getPhoneNumber(),
                    Toast.LENGTH_LONG)
                    .show();
            /////


            //list_of_messages.setHasFixedSize(true);
            final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setStackFromEnd(true);
            list_of_messages.setLayoutManager(linearLayoutManager);


            options =
                    new FirebaseRecyclerOptions.Builder<ChatMessage>()
                            .setQuery(query,new SnapshotParser<ChatMessage>() {
                                @NonNull
                                @Override
                                public ChatMessage parseSnapshot(@NonNull DataSnapshot snapshot) {
                                    return new ChatMessage(snapshot.child("messageUser").getValue().toString(),
                                            snapshot.child("messageText").getValue().toString());


                                }
                            })


                            .build();


            if (messageType) {
                messageType = false;
            } else {
                messageType = true;
            }

            ////////////////////////////////////////////////////////////


            //////////////////////////////////////////////////////////////////////



            adapter = new FirebaseRecyclerAdapter<ChatMessage, ChatHolder>(options) {



                @Override
                public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    // Create a new instance of the ViewHolder, in this case we are using a custom
                    // layout called R.layout.message for each item


                    View view = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.chats_layout_out, parent, false);


                    return new ChatHolder(view);

                }





                @Override
                protected void onBindViewHolder(ChatHolder holder, int position, ChatMessage model) {

                     //String ref = adapter.getRef(position).getKey();
                   // getSnapshots().getSnapshot(position).child("messageUser");

                  //  Toast.makeText(ChatWindow.this, getSnapshots().getSnapshot(position).child("messageUser").getValue().toString(), Toast.LENGTH_SHORT).show();


                    holder.layoutIn.setVisibility(View.VISIBLE);
                    holder.layoutOut.setVisibility(View.VISIBLE);




                              holder.messageTextIn.setText(model.getMessageText());
                              // holder.messageUser.setText("");

                              // Format the date before showing it
                              holder.messageTimeIn.setText(DateFormat.format("HH:mm:ss",
                                      model.getMessageTime()));

                       // ChatMessage mChat = chatList.get(position);

                        holder.messageTextOut.setText(model.getMessageText());
                       // holder.messageTextIn.setVisibility(View.GONE);
                    // holder.messageUser.setText("");


                    // Format the date before showing it
                    holder.messageTimeOut.setText(DateFormat.format("HH:mm:ss",
                            model.getMessageTime()));


                }
            };

            list_of_messages.scrollToPosition(adapter.getItemCount() - 1);


            list_of_messages.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            adapter.startListening();


        }


    }


    class ChatHolder extends RecyclerView.ViewHolder {

        TextView messageUserIn, messageTextIn, messageTimeIn, messageUserOut, messageTextOut, messageTimeOut;
        LinearLayout layoutOut;
        LinearLayout layoutIn;

        public ChatHolder(View v) {
            super(v);

            messageTextIn = (TextView) v.findViewById(R.id.message_text_in);
            messageUserIn = (TextView) v.findViewById(R.id.message_user_in);
            messageTimeIn = (TextView) v.findViewById(R.id.message_time_in);

            messageTextOut = (TextView) v.findViewById(R.id.message_text_out);
            messageUserOut = (TextView) v.findViewById(R.id.message_user_out);
            messageTimeOut = (TextView) v.findViewById(R.id.message_time_out);
            messageUserIn.setVisibility(View.GONE);
            messageUserOut.setVisibility(View.GONE);
            layoutIn = (LinearLayout) v.findViewById(R.id.layout_in);
            layoutOut = (LinearLayout) v.findViewById(R.id.layout_out);


            // Set their text

        }


    }






}

现在,在聊天窗口的两侧,无论用户是谁,都显示相同的消息。我使用用户电话号码代替用户ID。

这是聊天室“ ebube”在firebase中的外观

“ ebube”:{

“ LZARv-CxDQ8w8mjW-mt”:{

“ messageText”:“ hi”,

“ messageTime”:“ 1550675324216”,

“ messageUser”:“ + 2347019081538”

}

}

我做了很多虚弱的尝试,到目前为止没有任何效果。

1 个答案:

答案 0 :(得分:0)

为发送者和接收者设置两种不同的布局。然后检查messageUser是否与登录用户相同,并相应地增加您的布局

供参考,请查看this