简体   繁体   English

如何让消息出现在不同的侧面?

[英]How to make messages appear on different sides?

I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides.我使用视频教程制作了一个聊天应用程序,但本教程没有展示如何让来自不同人的消息出现在不同的侧面。 The sender and receiver see all messages on the left.发送者和接收者看到左侧的所有消息。 Could you please give some advices on this?您能否就此提出一些建议? Thanks in advance.提前致谢。

Now it looks like this现在看起来像这样

我的应用

Main code主要代码

public class MainActivity extends AppCompatActivity {

private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==SIGN_IN_CODE) {
           if(requestCode == RESULT_OK) {
               Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
               displayAllMessages();
               } else {
                 Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
                 finish();
           }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activity_main=findViewById(R.id.activity_main);
        sendBtn = findViewById(R.id.btnSend);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText textField = findViewById(R.id.messageField);
                if(textField.getText().toString().equals(""))
                    return;
                FirebaseDatabase.getInstance().getReference().push().setValue(
                        new Message(
                                FirebaseAuth.getInstance().getCurrentUser().getEmail(),
                        textField.getText().toString()));
                textField.setText("");
            }
        });

        //Пользователь ещё не авторизован
        if (FirebaseAuth.getInstance().getCurrentUser()==null)
            startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
        //Пользователь авторизован
        else {
            Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
            displayAllMessages();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    private void displayAllMessages() {
        ListView listOfMessages = findViewById(R.id.list_of_messages);
        FirebaseListOptions<Message> options =
                new FirebaseListOptions.Builder<Message>()
                        .setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
                        .setLayout(R.layout.list_item)
                        .build();
        adapter = new FirebaseListAdapter<Message>(options){
            @Override
            protected void populateView(View v, Message model, int position) {
                TextView mess_user, mess_time;
                BubbleTextView mess_text;
                mess_user = v.findViewById(R.id.message_user);
                mess_time = v.findViewById(R.id.message_time);
                mess_text = v.findViewById(R.id.message_text);
                mess_user.setText(model.getUserName());
                mess_text.setText(model.getTextMessage());
                mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
            }
        };
        listOfMessages.setAdapter(adapter);
    }
    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

Message Class消息 Class

public class Message {
    private String UserName;
    private String TextMessage;
    private long MessageTime;

    public Message() {}
    public Message (String UserName, String TextMessage){
        this.UserName = UserName;
        this.TextMessage = TextMessage;

        this.MessageTime = new Date().getTime();
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getTextMessage() {
        return TextMessage;
    }

    public void setTextMessage(String textMessage) {
        TextMessage = textMessage;
    }

    public long getMessageTime() {
        return MessageTime;
    }

    public void setMessageTime(long messageTime) {
        MessageTime = messageTime;
    }
}

Main XML主XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/activity_main">

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/btnSend"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:src="@drawable/ic_send_button"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/text_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@id/btnSend"
    >
    <EditText
        android:id="@+id/messageField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint=" Message..."
        />
</com.google.android.material.textfield.TextInputLayout>

<ListView
    android:id="@+id/list_of_messages"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/text_layout"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:divider="@android:color/transparent"
    android:dividerHeight="12dp"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:stackFromBottom="true"
    android:transcriptMode="alwaysScroll">
</ListView>

</RelativeLayout>

XML for the message bubbles XML 用于消息气泡

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/message_user"
        android:textStyle="normal|bold"
    />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:id="@+id/message_time"
    />

    <com.github.library.bubbleview.BubbleTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:id="@+id/message_text"
        android:layout_marginTop="9dp"
        android:layout_below="@id/message_user"
        android:textSize="18sp"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#fff"
        android:padding="10dp"
        app:angle="10dp"
        app:arrowWidth="8dp"
        app:arrowHeight="10dp"
        app:arrowPosition="10dp"
        app:bubbleColor="#03dac5"
    />

</RelativeLayout>

Try adding layout_gravity attribute in your BubbleTextView when you need this like this:当您需要时,请尝试在 BubbleTextView 中添加 layout_gravity 属性,如下所示:

android:layout_gravity="right"

Every user will have a unique email - Let say here in the example - d@mail.ru is your email.每个用户都会有一个独特的 email - 让我们在示例中说 - d@mail.ru 是您的 email。 You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.您需要添加用户逻辑以动态检查以确定您希望气泡测试布局是左还是右。

Update the message bubble layout.更新消息气泡布局。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/message_user"
        android:textStyle="normal|bold"
    />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:id="@+id/message_time"
    />

    <com.github.library.bubbleview.BubbleTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:id="@+id/message_text"
        android:layout_marginTop="9dp"
        android:layout_below="@id/message_user"
        android:textSize="18sp"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#fff"
        android:padding="10dp"
        app:angle="10dp"
        app:arrowWidth="8dp"
        app:arrowHeight="10dp"
        app:arrowPosition="10dp"
        app:bubbleColor="#03dac5"
    />

</RelativeLayout>

Adapter code:- you can update as you need either LEFT or RIGHT.适配器代码:- 您可以根据需要向左或向右进行更新。

       adapter = new FirebaseListAdapter<Message>(options){
                    @Override
                    protected void populateView(View v, Message model, int position) {
                        TextView mess_user, mess_time;
                        BubbleTextView mess_text;
                        RelativeLayout Layout = v.findViewById(R.id.parentlayout);
                        mess_user = v.findViewById(R.id.message_user);
                        mess_time = v.findViewById(R.id.message_time);
                        mess_text = v.findViewById(R.id.message_text);
                        mess_user.setText(model.getUserName());
                        mess_text.setText(model.getTextMessage());
                        mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));

                       if(!model.getUserName().equals("d@mail.ru")) {
                       mess_text.setGravity(Gravity.LEFT)
                      } else {
                        mess_text.setGravity(Gravity.RIGHT)
                     }
               }
          };

Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java检查此链接作为参考 - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM