안드로이드 앱 개발

RecyclerView 사용방법 - Listview 본문

안드로이드앱/RecyclerView

RecyclerView 사용방법 - Listview

스텝바이스텝안드로이드 2021. 3. 25. 23:59

1. RecyclerView를 사용할 Activity나 Fragment.xml에 

RecyclerView 위젯을 추가한다.

 

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="@color/white">

    <RelativeLayout
        android:id="@+id/topRl"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#ffffff">

        <TextView
            android:id="@+id/joinTv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"

            android:fontFamily="@font/notosansmonocjkkrbold"
            android:text="메모장"
            android:textColor="#211f1f"
            android:textSize="20sp"
            android:textStyle="bold" />


    </RelativeLayout>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/topRl"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerview_memo"
                android:layout_width="match_parent"
                android:layout_height="match_parent">


            </androidx.recyclerview.widget.RecyclerView>


        </RelativeLayout>


    </ScrollView>


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/botLl"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"

        android:layout_margin="16dp"
        android:backgroundTint="@color/ivory"
        android:src="@drawable/white_cross"
        app:borderWidth="0dp"

        app:elevation="1dp"
        app:tint="@null" />


</RelativeLayout>

* scrollview 안에 바로 recyclerview만 넣으면 스크롤의 오류가 있다고 하니 유의하자

 

2. RecyclerView의 개별 row (item) xml을 작성만든다.

res>layout> item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/single_row_cardview_memo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:backgroundTint="@color/ivory"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical"


    android:layout_marginBottom="1dp"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    android:layout_marginStart="2dp"
    android:layout_marginEnd="2dp"


    app:cardCornerRadius="10dp">

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


        <TextView
            android:id="@+id/titleTvForMemo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:fontFamily="@font/notosanscjkkrmedium"
            android:text="미입력_제목"
            android:textColor="@color/mainGrey"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/dateTvForMemo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/titleTvForMemo"
            android:layout_marginLeft="10dp"

            android:fontFamily="@font/notosanscjkkrmedium"
            android:text="메모가 저장된 날짜"
            android:textColor="@color/mainGreyFor50"
            android:textSize="12sp" />


        <TextView
            android:id="@+id/contentTvForMemo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/dateTvForMemo"
            android:layout_marginLeft="10dp"

            android:fontFamily="@font/notosanscjkkrmedium"
            android:text="010-3044-5548"
            android:textColor="@color/mainGrey"
            android:textSize="15sp" />


    </LinearLayout>






</androidx.cardview.widget.CardView>

 

3. RecyclerAdapter.java를 만들어준다.

public class RecyclerAdapter_Memo extends RecyclerView.Adapter<RecyclerAdapter_Memo.ViewHolder_Memo> {

    ArrayList<MemoClass> list;

    RecyclerAdapter_Memo(ArrayList<MemoClass> list) {
        this.list = list;
    }


    @NonNull
    @Override
    public ViewHolder_Memo onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.recycler_view_row_memo, parent, false);


        return new ViewHolder_Memo(view);

    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder_Memo holder, int position) {

        //====================date====================
        //현재시간을 msec 으로 구한다.
        long now = System.currentTimeMillis();
        // 현재시간을 date 변수에 저장한다.
        Date date = new Date(now);
        // 시간을 나타냇 포맷을 정한다 ( yyyy/MM/dd 같은 형태로 변형 가능 )
        SimpleDateFormat sdfNow = new SimpleDateFormat("yyyyMMddhhmmss");

        // nowDate 변수에 값을 저장한다.
        String nowYear = sdfNow.format(date).substring(0, 4);
        String nowMonthDay = sdfNow.format(date).substring(4, 8);

        //메모의 데이터 구하기
        String tmpDate = list.get(position).date;
        String memoYear = tmpDate.substring(0, 4);
        String memoMonthDay = tmpDate.substring(4, 8);

        String dspDateStr;
        if (nowYear.equals(memoYear)) { //현재 년도와 메모의 저장된 년도가 같으면
            if (nowMonthDay.equals(memoMonthDay)) { //월,일도 같으면
                dspDateStr = tmpDate.substring(8, 10) + "시 " + tmpDate.substring(10, 12) + "분";
            } else { //다르면
                dspDateStr = tmpDate.substring(4, 6) + "월 "
                        + tmpDate.substring(6, 8) + "일";
            }
        } else { //다르면
            dspDateStr = tmpDate.substring(0, 4) + "년 " + tmpDate.substring(4, 6) + "월 "
                    + tmpDate.substring(6, 8) + "일";
        }

        //==============================title===============================

        String titleStr = list.get(position).title.trim();

        if (titleStr.equals("미입력_제목")) {
            holder.title.setVisibility(View.GONE);
        } else {
            holder.title.setText(list.get(position).title);
        }


        holder.date.setText(dspDateStr);
        holder.content.setText(list.get(position).content);
    }

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


    class ViewHolder_Memo extends RecyclerView.ViewHolder {
        CardView cardView;
        TextView title, date, content;

        public ViewHolder_Memo(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.single_row_cardview_memo);
            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("recyclerbiew", "ㅎㅎ");
                }
            });
            title = itemView.findViewById(R.id.titleTvForMemo);
            date = itemView.findViewById(R.id.dateTvForMemo);
            content = itemView.findViewById(R.id.contentTvForMemo);
        }
    }
}


 

4. 마지막으로 RecyclerView를 사용할 Activity나 fragment.java에 

객체를 생성하고 연결해준다. 

 

RecyclerView recyclerView;
adapter_memo = new RecyclerAdapter_Memo(arr);
        recyclerView = rootview.findViewById(R.id.recyclerview_memo);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter_memo);

 

 

+ 아이템들의 클릭리스너를 달고 싶다면

어댑터 코드의 itemview에 click listener를 달아야한다

 

listview처럼 setOnItemClickListener 아예 없음

class ViewHolder_Memo extends RecyclerView.ViewHolder {
        CardView cardView;
        TextView title, date, content;

        public ViewHolder_Memo(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.single_row_cardview_memo);
            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("recyclerbiew", "ㅎㅎ");
                }
            });
            title = itemView.findViewById(R.id.titleTvForMemo);
            date = itemView.findViewById(R.id.dateTvForMemo);
            content = itemView.findViewById(R.id.contentTvForMemo);
        }
    }