android RecyclerView 심플 구현. kotlin

텍스트뷰만 있는 간단한 RecyclerView 구현이다.


activity layout xml 파일에 RecyclerView 을 추가한다.

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/text_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>


listitem_contents.xml 파일을 layout 폴더에 추가한다.

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" />


Adapter 클래스를 추가한다.


class ContentsAdapter(private val textList: MutableList<String>) :
RecyclerView.Adapter<ContentsAdapter.ContentsHolder>() {

class ContentsHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)


interface ItemClick
{
fun onClick(view: View, position: Int)
}
var itemClick: ItemClick? = null

override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): ContentsAdapter.ContentsHolder {
val textView = LayoutInflater.from(parent.context)
.inflate(R.layout.listitem_contents, parent, false) as TextView
return ContentsHolder(textView)
}

override fun onBindViewHolder(holder: ContentsHolder, position: Int) {
holder.textView.text = textList[position] ?: ""

if(itemClick != null)
{
holder?.textView?.setOnClickListener { v ->
itemClick?.onClick(v, position)
}
}
}

override fun getItemCount() = textList.size
}



Activity onCreate 코드에서 다음과 같이 추가한다.
itemClick은 클릭했을때의 리스너다. 클릭 처리가 없다면 삭제한다.

var list = mutableListOf<String>()
var viewAdapter: RecyclerView.Adapter<*> = ContentsAdapter(list)
(viewAdapter as ContentsAdapter).itemClick = object: ContentsAdapter.ItemClick {
override fun onClick(view: View, position: Int) {
try {
            <You Code>
} catch (e: Exception) {

}
}
}
val recyclerView : RecyclerView = findViewById(R.id.body_text_list)
recyclerView.adapter = viewAdapter



댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore

플러터(flutter) 개발 참고 사이트들.