250x250
Notice
02-05 00:01
관리 메뉴

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

[안드로이드] 리사이클러뷰(RecyclerView) 어댑터 베이스 정리 코드 (복붙용) 본문

안드로이드/코틀린 & 아키텍처 & Recent

[안드로이드] 리사이클러뷰(RecyclerView) 어댑터 베이스 정리 코드 (복붙용)

막무가내막내 2021. 1. 16. 00:12
728x90

[2021-04-14 업데이트]

 

디프유틸 사용한것

youngest-programming.tistory.com/474

 

[안드로이드] RecyclerView -> ListAdapter + Diffutil 예제 정리

[개념(출처) 참고 및 공부자료들] thdev.tech/kotlin/2020/09/22/kotlin_effective_03/ data class를 활용하여 RecyclerView.DiffUtil을 잘 활용하는 방법 | I’m an Android Developer. thdev.tech velog.io/@l2h..

youngest-programming.tistory.com

 

[Adapter]

버전 1 

package com.mtjin.cnunoticeapp.views.bachelor

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.mtjin.cnunoticeapp.R
import com.mtjin.cnunoticeapp.data.bachelor.BachelorNotice
import com.mtjin.cnunoticeapp.databinding.ItemBachelorBinding

class BachelorAdapter(
    private val itemClick: (BachelorNotice) -> Unit,
    private val numClick: (BachelorNotice) -> Unit
) :
    RecyclerView.Adapter<BachelorAdapter.ViewHolder>() {

    private val items: ArrayList<BachelorNotice> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BachelorAdapter.ViewHolder {
        val binding: ItemBachelorBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_bachelor,
            parent,
            false
        )
        val viewHolder = ViewHolder(binding)
        binding.apply {
            root.setOnClickListener {
                itemClick(items[viewHolder.bindingAdapterPosition])
            }
            bachelorTvNum.setOnClickListener {
                numClick(items[viewHolder.bindingAdapterPosition])
            }
        }
        return viewHolder
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: BachelorAdapter.ViewHolder, position: Int) {
        items[position].let {
            holder.bind(it)
        }
    }

    class ViewHolder(private val binding: ItemBachelorBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: BachelorNotice) {
            binding.item = item
            binding.executePendingBindings()
        }
    }

    fun addItems(items: List<BachelorNotice>) {
        this.items.addAll(items)
        notifyDataSetChanged()
    }

    fun clear() {
        this.items.clear()
        notifyDataSetChanged()
    }

}

 

버전2

package com.mtjin.cnunoticeapp.views.board_list

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.mtjin.cnunoticeapp.R
import com.mtjin.cnunoticeapp.data.board_list.Board
import com.mtjin.cnunoticeapp.databinding.ItemBoardBinding

class BoardAdapter(private val itemClick: (Board) -> Unit) :
    RecyclerView.Adapter<BoardAdapter.ViewHolder>() {
    private val items = mutableListOf<Board>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding: ItemBoardBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_board,
            parent,
            false
        )
        return ViewHolder(binding).apply {
            binding.root.setOnClickListener { view ->
                val position = bindingAdapterPosition.takeIf { it != RecyclerView.NO_POSITION }
                    ?: return@setOnClickListener
                itemClick(items[position])
            }
        }
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        items[position].let {
            holder.bind(it)
        }
    }

    class ViewHolder(private val binding: ItemBoardBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(board: Board) {
            binding.item = board
            binding.executePendingBindings()
        }
    }

    fun addItems(items: List<Board>) {
        this.items.addAll(items)
        notifyDataSetChanged()
    }

    fun addItem(item: Board) {
        this.items.add(item)
        notifyDataSetChanged()
    }

    fun clear() {
        this.items.clear()
        notifyDataSetChanged()
    }
}

 

 

[액티비티, 프래그먼트]

private fun initAdapter() {
        binding.rvBoards.adapter = BoardAdapter(itemClick = { board ->
            val intent = Intent(this@BoardListActivity, BoardDetailActivity::class.java)
            intent.putExtra(EXTRA_BOARD, board)
            intent.putExtra(EXTRA_BOARD_NAME, viewModel.boardName.value)
            startActivity(intent)
        })
    }
 <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_boards"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/margin_28dp"
            android:clipToPadding="false"
            android:orientation="vertical"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@id/et_search"
            bind:boardEndlessScroll="@{vm}"
            bind:setBoardItems="@{vm.boardList}"
            tools:itemCount="5"
            tools:listitem="@layout/item_board" />

 

 

[아이템 xml]

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="item"
            type="com.mtjin.cnunoticeapp.data.board_list.Board" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout_board"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingStart="@dimen/padding_12dp"
        android:paddingTop="@dimen/padding_12dp"
        android:paddingEnd="@dimen/padding_12dp">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="@{item.title}"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_18sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="제목ㅁㅁㅁㅁㅁㅁㄴㅇㅁㅇㅇㄴㅁㅇasdasdㄴㅁㅇasdsad" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_4dp"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="@{item.content}"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_size_14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tv_title"
            tools:text="내용입니다 내용입니다 내용입니다 내용입니다 내용입니다 내용입니다 내용입니다" />

        <TextView
            android:id="@+id/tv_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_4dp"
            android:textSize="@dimen/text_size_10sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tv_content"
            bind:setBoardTime="@{item.id}"
            tools:text="12:30" />

        <TextView
            android:id="@+id/tv_comment_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawablePadding="@dimen/padding_4dp"
            android:text="@{String.valueOf(item.commentCount)}"
            android:textSize="@dimen/text_size_12sp"
            app:drawableStartCompat="@drawable/ic_baseline_mode_comment_12"
            app:layout_constraintBottom_toBottomOf="@id/tv_date"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@id/tv_date"
            tools:text="0" />

        <TextView
            android:id="@+id/tv_recomment_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/margin_12dp"
            android:drawablePadding="@dimen/padding_4dp"
            android:text="@{String.valueOf(item.recommendList.size())}"
            android:textSize="@dimen/text_size_12sp"
            app:drawableStartCompat="@drawable/ic_baseline_thumb_up_12"
            app:layout_constraintBottom_toBottomOf="@id/tv_date"
            app:layout_constraintEnd_toStartOf="@id/tv_comment_count"
            app:layout_constraintTop_toTopOf="@id/tv_date"
            tools:text="0" />


        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/height_1dp"
            android:layout_marginTop="@dimen/margin_4dp"
            android:background="@color/colorWhiteGray"
            app:layout_constraintTop_toBottomOf="@id/tv_date" />


    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

 

댓글과 공감은 큰 힘이 됩니다. 감사합니다. !!!

728x90
0 Comments
댓글쓰기 폼