본문 바로가기
Android

[Java] 하나의 RecyclerView에 서로 다른 뷰 넣기 ( TCP 채팅 예제 - 카카오톡 채팅화면)

by 오늘도 깨달았다 2022. 1. 12.
반응형

카카오톡 채팅화면처럼 내가 입력하는 내용들과 상대방이 입력하는 내용들이 서로 다른 뷰에 보여야 할 때 유용합니다.

 

저는 TCP 채팅을 구현하는 중 사용했으므로 예제도 그에 관련된 예제입니다.

 

1. 상대방이 입력한 채팅 내용을 담을 뷰 세팅 

 

- left_chat.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
    android:background="@color/white"
    android:paddingTop="12dp"
    android:paddingBottom="12dp">

    <TextView
        android:id="@+id/left_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="7dp"
        android:text="이름"
        android:textColor="@color/black"
        android:textSize="12sp"
        app:layout_constraintStart_toEndOf="@+id/left_profile"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/left_content"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="56dp"
        android:layout_marginTop="8dp"
        android:paddingLeft="16dp"
        android:paddingTop="4dp"
        android:paddingRight="16dp"
        android:paddingBottom="4dp"
        android:maxWidth="250dp"
        android:text="상대방이 보낸 메세지"
        android:textColor="#333d4b"
        android:textSize="15dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/left_name" />

    <TextView
        android:id="@+id/left_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:text="00:00"
        android:textColor="#b9bcce"
        android:textSize="10sp"
        app:layout_constraintBottom_toBottomOf="@+id/left_content"
        app:layout_constraintStart_toEndOf="@+id/left_content" />

    <ImageView
        android:id="@+id/left_profile"
        android:layout_width="48dp"
        android:layout_height="51dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.7"
        app:srcCompat="@drawable/ic_profile" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

2. 내가 입력한 채팅 내용을 담을 뷰 세팅

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
    android:background="@color/white"
    android:paddingTop="12dp"
    android:paddingBottom="12dp">

    <TextView
        android:id="@+id/right_content"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="15dp"
        android:paddingLeft="16dp"
        android:paddingTop="4dp"
        android:paddingRight="16dp"
        android:maxWidth="250dp"
        android:paddingBottom="4dp"
        android:text="내가 보낸 메세지"
        android:textColor="@color/black"
        android:textSize="15dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:text="00:00"
        android:textColor="#b9bcce"
        android:textSize="10sp"
        app:layout_constraintBottom_toBottomOf="@+id/right_content"
        app:layout_constraintEnd_toStartOf="@+id/right_content" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

3. 두 뷰를 담을 화면 및 RecyclerView 

 

 

- activity_chat

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/chat_recycler"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/chat_ET"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:inputType="textMultiLine"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <Button
            android:id="@+id/chat_send_btn"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:fontFamily="@font/poppins"

            android:text="전송"
            android:textColor="#FFFFFF" />
    </LinearLayout>
</LinearLayout>

 

4. 상대방이 보낸 내용인지 내가 보낸 내용인지 확인할 ViewType 및 아이템 클래스

 

public class ViewType {
    public static final int LEFT_CHAT = 1;
    public static final int RIGHT_CHAT = 2;
}

 


public class ChatItem {


    String nickname;
    String content;
    String time;
    String profile_img;
    int viewType;

    public ChatItem(String nickname, String profile_img, String content , String time, int viewType) {
        this.content = content;
        this.profile_img= profile_img;
        this.nickname = nickname;
        this.time = time;
        this.viewType = viewType;
    }

    public String getProfile_img() {
        return profile_img;
    }

    public void setProfile_img(String profile_img) {
        this.profile_img = profile_img;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public int getViewType() {
        return viewType;
    }

    public void setViewType(int viewType) {
        this.viewType = viewType;
    }
}

 

 

5. 액티비티 


public class ChatActivity extends AppCompatActivity {
    private final String TAG = "ChatActivity";

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

        mRecyclerView = findViewById(R.id.chat_recycler);

        chatting_message = findViewById(R.id.chat_ET);
        chatting_send_btn = findViewById(R.id.chat_send_btn);

        LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);

        mRecyclerView.setLayoutManager(manager); // LayoutManager 등록
        mAdapter = new ChatAdapter(chatItem);
        mRecyclerView.setAdapter(mAdapter);  // Adapter 등록

        Date today = new Date();


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
        String nowtime = sdf.format(today);
                    

        if (chatItem == null) {
            chatItem = new ArrayList<>();


            ChatItem send_message = new ChatItem("닉네임", "imgsrc", "내가쓴거야", nowtime, 2);
            ChatItem receive_message = new ChatItem("받는사람", "imgsrc", "상대방이쓴거", nowtime, 1);
            

            chatItem.add(send_message);
            mAdapter.notifyDataSetChanged();


        }

    }
}

 

6. ChatItem을 넣어줄 RecyclerView Adapter

 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.football.Class.Admin_matching_applicant_Data;
import com.example.football.Class.ChatItem;
import com.example.football.Class.Matching_getData;
import com.example.football.Class.Matching_user_check;
import com.example.football.Class.ViewType;
import com.example.football.R;

import org.jetbrains.annotations.NotNull;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private ArrayList<ChatItem> myDataList = null;
    Context context;

    public ChatAdapter(ArrayList<ChatItem> dataList) {
        myDataList = dataList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        context = parent.getContext();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (viewType == ViewType.LEFT_CHAT) {
            view = inflater.inflate(R.layout.left_chat, parent, false);
            return new LeftViewHolder(view);
        } else {
            view = inflater.inflate(R.layout.right_chat, parent, false);
            return new RightViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof LeftViewHolder) {
            ((LeftViewHolder) viewHolder).name.setText(myDataList.get(position).getNickname());
            if (myDataList.get(position).getProfile_img() != null) {
                String imagestr = myDataList.get(position).getProfile_img();

                Glide.with(context).load(imagestr).circleCrop().into(((LeftViewHolder) viewHolder).profile);
            }
            ((LeftViewHolder) viewHolder).content.setText(myDataList.get(position).getContent());
            String resultTime = null;

            try {
                String getTime = myDataList.get(position).getTime();


                SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
                SimpleDateFormat getFormat = new SimpleDateFormat("HH:mm", Locale.KOREA);
                Date formatDate = transFormat.parse(getTime);
                assert formatDate != null;
                resultTime = getFormat.format(formatDate);

                String [] split = resultTime.split(":");

                int time = Integer.parseInt(split[0]);


                if (time > 12){
                    int hour = time-12;

                    resultTime = "오후 "+ hour + ":" + split[1];


                }else {

                    resultTime = "오전 "+ time + ":" + split[1];

                }

            }catch (ParseException e){

                e.printStackTrace();
            }



            ((LeftViewHolder) viewHolder).time.setText(resultTime);
        } else {
            ((RightViewHolder) viewHolder).content.setText(myDataList.get(position).getContent());

            String resultTime = null;

            try {
                String getTime = myDataList.get(position).getTime();


                SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
                SimpleDateFormat getFormat = new SimpleDateFormat("HH:mm", Locale.KOREA);
                Date formatDate = transFormat.parse(getTime);
                assert formatDate != null;
                resultTime = getFormat.format(formatDate);

                String [] split = resultTime.split(":");

                int time = Integer.parseInt(split[0]);


                if (time > 12){
                    int hour = time-12;

                    resultTime = "오후 "+ hour + ":" + split[1];


                }else {

                    resultTime = "오전 "+ time + ":" + split[1];

                }

            }catch (ParseException e){

                e.printStackTrace();
            }



            ((RightViewHolder) viewHolder).time.setText(resultTime);
        }
    }

    @Override
    public int getItemCount() {
        return myDataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return myDataList.get(position).getViewType();
    }


    public class LeftViewHolder extends RecyclerView.ViewHolder {
        ImageView profile;
        TextView content;
        TextView name;
        TextView time;

        LeftViewHolder(View itemView) {
            super(itemView);

            content = itemView.findViewById(R.id.left_content);
            name = itemView.findViewById(R.id.left_name);
            time = itemView.findViewById(R.id.left_time);
            profile = itemView.findViewById(R.id.left_profile);

        }
    }

    public class RightViewHolder extends RecyclerView.ViewHolder {
        TextView content;
        TextView time;

        RightViewHolder(View itemView) {
            super(itemView);

            content = itemView.findViewById(R.id.right_content);
            time = itemView.findViewById(R.id.right_time);
        }
    }

}

 

시간은 오전 12:00  와 같이 나오게 변형시켰고 두개의 뷰홀더로 하나의 리사이클러뷰에 다른 뷰들을 담는 예제였습니다.

 

 

반응형

댓글