본문 바로가기
android

[kotlin] 리사이클러뷰 예제

by liz_devel 2021. 7. 28.

BlogAdapter.kt

class BlogAdapter : RecyclerView.Adapter<BlogAdapter.ViewHolder>() {

    var datas = mutableListOf<SearchData>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = RvBlogBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int = datas.size

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

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

        fun bind(item: SearchData) { //데이터 넣기
            binding.tvTitle.text = item.title
            binding.tvContents.text = item.description
        }
    }


}

 

SearchData.kt

data class SearchData(
    // 게시글 제목
    val title : String = "",

    // 게시글 내용
    val description : String = ""
)

 

rv_blog.xml

<?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:orientation="vertical"
    android:layout_margin="8dp">
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="30dp"/>
    <TextView
        android:id="@+id/tv_contents"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>
</LinearLayout>

 

frg_blog.xml

<?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="match_parent"
    android:layout_margin="8dp"
    android:orientation="vertical">

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

        <EditText
            android:id="@+id/et_blog"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:hint="블로그 검색어를 입렵해주세요" />

        <Button
            android:id="@+id/btn_blog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="검색" />

    </LinearLayout>
    
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_blog"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
반응형