RecyclerView
RecyclerView는 많은 수의 데이터 집합을 하나하나의 아이템 단위로 구성하여 화면에 출력을 해 주는 뷰 그룹이며
한 화면에 표시되기 어려운 많은 데이터를 스크롤 가능한 리스트로 표시해주는 위젯입니다.
리사이클 러뷰는 리스트뷰와 목적이나 동작 방식이 비슷 하지만 리사이클 러뷰는 리스트뷰에 비해 더 유연하고 성능적인 면도 개선을 한 위젯입니다.
구글에서도 리스트뷰 대신 리사이클 러뷰를 사용하도록 권고하고 있습니다.
리사이클 러뷰는 이름 그대로 각각의 아이템 뷰를 재활용하여 스크롤하여 새로 생길 뷰 에 할당을 하여 메모리면에서나 성능면에서 리스트뷰보다 더 우세합니다.
리사이클 러뷰는 기본적으로 뷰 홀더(ViewHolder)패턴을 사용합니다.
리스트뷰는 수직방향으로만 나열이 가능했다면 리사이클러뷰는 수평으로도 나열이 가능합니다.
리사이클 러뷰에서 아이템뷰가 나열되는 형태를 관리하기 위해 레이아웃 매니저를 제공합니다.
작업 순서
메인 액티비티에 리사이클러뷰 추가 > 아이템뷰 레이아웃 추가 >
리사이클러뷰 어댑터 구현 > 어댑터, 레이아웃 매니저 지정
아래는 연락처를 구현한 리사이클 러뷰를 만드는 제작 과정입니다.
먼저 build.grable. 파일에 아래와 같이 추가합니다.
dependencies {
...
implementation "androidx.recyclerview:recyclerview:1.1.0"
}
Data클래스를 아래와 같이 만들어줍니다.
package com.example.newlistview
class Contacts(val name: String, val tel: String) {
}
메인 액티비티에 아래와 같이 List에 데이터를 넣어줍니다.
class MainActivity : AppCompatActivity() {
val contactList : List<Contacts> = listOf(
Contacts("1", "010-0000-0000"),
Contacts("2", "010-0000-0001"),
Contacts("3", "010-0000-0002"),
Contacts("4", "010-0000-0003"),
Contacts("5", "010-0000-0004"),
Contacts("6", "010-0000-0005"),
Contacts("7", "010-0000-0006"),
Contacts("8", "010-0000-0007"),
Contacts("9", "010-0000-0008"),
Contacts("10", "010-0000-0009"),
Contacts("11", "010-0000-00010")
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
MainActivity에 리싸이클 러뷰를 추가하고 추후에 구현하기 위해 버튼, 텍스트뷰를 배치합니다
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycle_1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_margin="8dp"
android:id="@+id/btn_1"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_margin="8dp"
android:id="@+id/btn_2"
/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_margin="8dp"
android:id="@+id/btn_3"
/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="test"
android:textSize="6sp"
android:gravity="center"
android:layout_margin="8dp"
android:id="@+id/btn_4"
/>
</LinearLayout>
</LinearLayout>
라이 아웃이 위와 같이 돼야 정상입니다.
리스트의 모델이 될 레이아웃을 만듭니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="50dp">
<TextView
android:id="@+id/txt_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txt_phone_num"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
보면 아시듯 위에는 이름 아래는 번호가 출력되게 할 예정입니다.
리싸이클 러뷰의 어댑터에 사용할 뷰 홀더를 만들어줍니다.
바로 직전에 만든 레이아웃에 있는 각 뷰들의 이름과 Contacts의 변수를 연결해줍니다.
class ContactsViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var view : View = v
fun bind(item : Contacts) {
view.txt_name.text = item.name
view.txt_phone_num.text = item.tel
}
}
익스텐션 플러그인을 사용했습니다.
다음 어댑터를 만들어줍니다.
class ContactsListAdapter(val itemList : List<Contacts>) : RecyclerView.Adapter<ContactsViewHolder>()
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactsViewHolder {
val inflatedView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_contacts, parent, false)
return ContactsViewHolder(inflatedView)
}
override fun getItemCount() = itemList.size
override fun onBindViewHolder(holder: ContactsViewHolder, position: Int) {
val item = itemList[position]
holder.apply {
bind(item)
}
}
}
최종적으로 메인 액티비티와 어댑터를 연결해주면 끝이 납니다
추가 구현을 위해 메인 액티비티에 뷰 바인딩을 했지만 사용 안 하셔도 됩니다.
아래는 실행화면입니다.
'Android' 카테고리의 다른 글
[Android] 사용 중인 플러그인 (0) | 2022.12.06 |
---|---|
[Android] 디자인 패턴 (0) | 2022.07.27 |
[Android] ListView 사용 (0) | 2021.02.15 |
[Android] View Binding (0) | 2021.02.01 |