관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[안드로이드] 리사이클러뷰(RecyclerView) 표본 본문

안드로이드/자바 & Previous

[안드로이드] 리사이클러뷰(RecyclerView) 표본

막무가내막내 2019. 5. 19. 13:54
728x90

 

리사이클러뷰 표본 예시 포스팅하겠습니다.

저는 context와 items를 한번에 넣어주기 위해 생성자를 저렇게 2개를 받았지만 보통의 경우 둘 중 하나를 받는 것 같습니다.( 가르치시는분이나 블로그마다 달라서...)

 

어댑터부분 (그냥 쓴거와 null분기문으로 처리한거 두가지 올려봅니다)

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mtjin.studdytogether.R;
import com.mtjin.studdytogether.rtdb_model.Comment;
import com.mtjin.studdytogether.activity.PhotoZoomActivity;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
    Context context;
    ArrayList<Comment> items = new ArrayList<Comment>();


    public  CommentAdapter(ArrayList<Comment> items, Context context){
        this.context =  context;
        addItems(items);
    }

    @Override //어댑터에서 관리하는 아이템의 개수를 반환
    public int getItemCount() {
        return items.size();
    }

    //아이템을 추가해주고싶을때 이거쓰면됨
    public  void addItem(Comment item){
        items.add(item);
    }

    //한꺼번에 추가해주고싶을떄
    public void addItems(ArrayList<Comment> items){
        this.items = items;
    }

    //아이템 전부 삭제
    public void clear(){
        items.clear();
    }

    @NonNull
    @Override //뷰를 담을 수 있는 뷰홀더를 생성해줍니다. (이 뷰 홀더의 기준대로 리사이클러뷰가 만들어집니다.) 
    public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_comment, viewGroup, false); //우리가쓸려는 chatMessage아이템의 뷰객체 생성
        return new CommentViewHolder(view); //각각의 chatMessage아이템을 위한 뷰를 담고있는 뷰홀더객체를 반환한다.
    }

    @Override //홀더에 맞게 데이터들을 세팅해줍니다.
    public void onBindViewHolder(@NonNull CommentViewHolder holder, int i) {
        final Comment model = items.get(i);
        holder.nickNameTextView.setText(model.getNickName());
        holder.ageTextView.setText(model.getAge());
        holder.dateTextView.setText(model.getDate());
        holder.messageTextView.setText(model.getMessage());
        if (model.getImage().equals("basic")) { //프로필사진이 없는경우
            Glide.with(context).load("https://firebasestorage.googleapis.com/v0/b/studdytogether.appspot.com/o/Basisc%2FbasicProfile.png?alt=media&token=dd0e0e17-a057-40a4-ae7f-364fa529e2").into(holder.profileCircleImageView);
        } else {
            Glide.with(context).load(model.getImage()).into(holder.profileCircleImageView);
        }
    }

    //뷰들을 바인딩 해줍니다.
    public class CommentViewHolder extends RecyclerView.ViewHolder {
        CircleImageView profileCircleImageView;
        TextView nickNameTextView;
        TextView ageTextView;
        TextView dateTextView;
        TextView messageTextView;

        public CommentViewHolder(@NonNull final View itemView) {
            super(itemView);
            profileCircleImageView = itemView.findViewById(R.id.comment_iv_profile);
            nickNameTextView = itemView.findViewById(R.id.comment_tv_name);
            ageTextView = itemView.findViewById(R.id.comment_tv_age);
            dateTextView = itemView.findViewById(R.id.comment_tv_date);
            messageTextView = itemView.findViewById(R.id.comment_tv_message);
        }



    }
}
package com.mtjinse.myapplication.activity.adapters;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mtjinse.myapplication.R;
import com.mtjinse.myapplication.activity.activities.PhotoZoomInActivity;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

import android.content.Intent;

import com.mtjinse.myapplication.activity.models.Comment;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
    static final String TAG = "CommentAdapter";
    Context context;
    ArrayList<Comment> items = new ArrayList<Comment>();

    public CommentAdapter(ArrayList<Comment> items, Context context) {
        this.context = context;
        addItems(items);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
    @NonNull
    @Override
    public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_comment, viewGroup, false);
        return new CommentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CommentViewHolder holder, int i) {
        final Comment model = items.get(i);
        if(model != null) {
            holder.dateTextView.setText(model.getDates());
            holder.commentTextView.setText(model.getComment());
            holder.nickNameTextView.setText(model.getNickName());
            if (model.getProfileImage().equals("basic")) { //프로필사진이 없는경우
                holder.profileCircleImageView.setImageResource(R.drawable.com_facebook_profile_picture_blank_square);
            } else {
                Glide.with(context).load(model.getProfileImage()).into(holder.profileCircleImageView);
            }

            //친구사진 누른경우
            holder.profileCircleImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, PhotoZoomInActivity.class);
                    intent.putExtra("photoView", model.getProfileImage());
                    context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            });
        }else{
            Log.d(TAG, "onBindViewHolder model null");
        }
    }

    @Override
    public int getItemCount() {
        if(items == null){
            return  0;
        }else {
            return items.size();
        }
    }


    //뷰들을 바인딩 해줍니다.
    public class CommentViewHolder extends RecyclerView.ViewHolder {
        CircleImageView profileCircleImageView;
        TextView nickNameTextView;
        TextView commentTextView;
        TextView dateTextView;

        public CommentViewHolder(@NonNull final View itemView) {
            super(itemView);
            profileCircleImageView = itemView.findViewById(R.id.commentItem_iv_photo);
            nickNameTextView = itemView.findViewById(R.id.commentItem_tv_nickname);
            commentTextView = itemView.findViewById(R.id.commentItem_tv_comment);
            dateTextView = itemView.findViewById(R.id.commentItem_tv_date);
        }
    }

    //아이템을 추가해주고싶을때 이거쓰면됨
    public void addItem(Comment item) {
        items.add(item);
    }

    //한꺼번에 추가해주고싶을떄
    public void addItems(ArrayList<Comment> items) {
        this.items = items;
    }

    //아이템 전부 삭제
    public void clear() {
        items.clear();
    }
}

 

여기에 가끔 리사이클러뷰 아이템들이 화면에 겹쳐서 보이거나 하나의 아이템의 글이 다른 아이템에도 보이는 그런 현상이 발생할 때가 있다.

그럴때는 이걸 추가로 오버라이드 해보길바란다.

@Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

 

 

MODEL

public class Comment {
    private String nickName;
    private String age;
    private String image;
    private String date;
    private String message;
    private String uid;

    public  Comment(){}

    public Comment(String nickName, String age, String image, String date, String message, String uid) {
        this.nickName = nickName;
        this.age = age;
        this.image = image;
        this.date = date;
        this.message = message;
        this.uid = uid;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getImage() {
        return image;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public void setImage(String image) {

        this.image = image;
    }
}

 

Comment Item view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:padding="3dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center_vertical">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/comment_iv_profile"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="top"
            android:src="@drawable/profile"
            app:civ_border_color="#FF000000"
            app:civ_border_width="1dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

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

                <TextView
                    android:id="@+id/comment_tv_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="5dp"
                    android:text="@string/nickName"
                    android:textColor="@color/textColor"
                    android:textSize="15dp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginRight="5dp"
                    android:text="|"
                    android:textColor="@color/textColor" />

                <TextView
                    android:id="@+id/comment_tv_age"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginRight="5dp"
                    android:text="10대"
                    android:textColor="@color/textColor"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginRight="5dp"
                    android:text="|"
                    android:textColor="@color/textColor" />

                <TextView
                    android:id="@+id/comment_tv_date"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="2019-04-30 12:30"
                    android:textColor="@color/textColor"
                    android:textStyle="bold" />

            </LinearLayout>

            <TextView
                android:id="@+id/comment_tv_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/round_gray_text"
                android:maxLength="150"
                android:maxLines="15"
                android:padding="10dp"
                android:textColor="@color/textColor"
                android:text="메세지 내용"
                android:textSize="15dp" />

        </LinearLayout>
    </LinearLayout>


</LinearLayout>

 

 

액티비티(데이터 추가는 뒷부분 코드에서 추가해줬으므로 생략)

   mCommentsRecyclerView = findViewById(R.id.comments_rev_comments);
        mWriteEditText = findViewById(R.id.comments_pt_write);
        mSendButton = findViewById(R.id.comments_btn_send);

        //아이템리스트
        mCommentList = new ArrayList<>();
        //리니어레이아웃으로 만들것으로 정의한다. (그리드뷰 쓰면 그리드뷰로 만들어진다.)
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); //레이아웃매니저 생성
        mCommentsRecyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL)); //아래구분선 세팅
        mCommentsRecyclerView.setLayoutManager(layoutManager); ////만든 레이아웃매니저 객체를(설정을) 리사이클러 뷰에 설정해줌
        //어댑터를 연결시켜준다.
        mCommentAdapter = new CommentAdapter(mCommentList, getApplicationContext());
        mCommentsRecyclerView.setAdapter(mCommentAdapter); 

 

 

추가적으로 리사이클러뷰 xml에 이렇게 해주면 리스트들을 레이아웃에서 어떻게 넣어질지 볼 수 있다.

 tools:listitem="@layout/minigram_item"
728x90
Comments