밍비
프로그램의 편린
밍비
전체 방문자
오늘
어제
  • 분류 전체보기 (64)
    • Spring (2)
    • TIL (23)
    • 프로그래머스 (12)
    • Udemy (16)
    • Typescript (2)
    • MERN (1)
    • AWS (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 리액트 프로젝트 만들기
  • 리스트 조회
  • state 관리
  • 서비스아키텍처
  • useNavigate
  • API 호출
  • DOM
  • overflow-wrap
  • 한입크기로잘라먹는리액트
  • Availability Zones
  • Edge Locations
  • 한입 크기로 잘라먹는 리액트
  • State 합치기
  • 리액트 생애주기
  • 데이터 수정
  • state 끌어올리기
  • AWS Regions
  • 리액트 reducer
  • useParams
  • useState
  • useRef
  • Page Moving
  • 함수형 update
  • 분산저장소
  • Points of Presence
  • 리액트
  • 컴포넌트트리
  • 수평 스케일링
  • 네이버커넥트
  • react

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
밍비

프로그램의 편린

[안드로이드] [코틀린] 리사이클러뷰에 뷰바인딩 적용하기
TIL

[안드로이드] [코틀린] 리사이클러뷰에 뷰바인딩 적용하기

2022. 7. 5. 11:52
728x90

안드로이드 공부의 가장 힘든 점이 프로그래밍패턴은 빠르게 바뀌는데, 그만큼 자료는 빠르게 바뀌지 않는다는 점이다...

findviewbyId만 쓰다가 저번 프로젝트 때 뷰바인딩을 처음 알게 됐고, 리사이클러뷰도 얼마전에...알게 됐다

그래서 이번에는 리사이클러뷰를 적용해서 페이지를 만들어보자고 다짐했다

근데,,리사이클러뷰에 대해 구글링해보니까 리사이클러뷰+findviewById를 쓰는 자료가 너무 많았다,,

 

그래서!!뷰바인딩을 이용한 리사이클러뷰 코드 짠 걸 공유하겠음

 

0. 뷰바인딩, 리사이클러뷰 불러오기

dataBinding{
    enabled = true
}
buildFeatures{
    viewBinding true
}

build.gradle의 모듈단위 파일에다가 추가해준다.

 

dependencies{
...
//조회화면 ui
implementation 'androidx.recyclerview:recyclerview:1.2.1'
}

그밑에 dependencies 안에 리사이클러뷰도 추가해준다.

 

 

1. Store.kt

package gdsc.knu.model
data class Store(
    val id: Long,
    val name: String,
    val description: String,
    val tel: String,
    val address: String,
    val lat: Double,
    val lon: Double,
    val menu: List<String>,
    val category: String

)

우선 데이터클래스를 선언해준다.

코틀린파일들 사이에 "model"이라는 이름의 패키지를 추가해서 그안에 써줬음

 

2. storeApis.kt

package gdsc.knu.api

import gdsc.knu.model.Store

fun getStore(id:Long): Store = Store(
    id,
    "모이다식탁",
    "경북대학교정문에서 대구공고로 내려오는 길에 해비치커피1층에 있습니다.^,^",
    "0507-1328-1097",
    "대구 북구 경대로7길 2 1층",
    66.87,
    127.32,
    listOf("소세지오므라이스","베이컨새우볶음밥"),
    "한식"

)

아직 데이터 받아오는 부분이 나오지 않아서 임시로 가짜데이터를 만들어줬다.

위의 데이터클래스에 해당하는 값을 하나하나 넣음

 

3. store_lookup.xml

<?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:id="@+id/linear_view"
    android:layout_width="match_parent"
    android:layout_height="380dp"
    android:layout_margin="8dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="294dp"
        android:layout_height="wrap_content"
        android:maxLines="3"
        android:padding="8dp"
        android:text="title"
        android:textColor="#222"
        android:textSize="22dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/description"
        android:layout_width="291dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="20dp"
        android:maxLines="3"
        android:padding="8dp"
        android:text="description"
        android:textColor="#666"
        android:textSize="14dp" />

    <TextView
        android:id="@+id/tel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="053-123-4567" />

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

        <TextView
            android:id="@+id/category"
            android:layout_width="95dp"
            android:layout_height="wrap_content"
            android:text="양식" />

        <TextView
            android:id="@+id/address"
            android:layout_width="152dp"
            android:layout_height="match_parent"
            android:maxLines="3"
            android:text="대구광역시" />

    </LinearLayout>

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

</LinearLayout>

정말 앙상한 디자인

 

4. menu_item.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="50dp"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/nameTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메뉴이름"
        android:textSize="20sp" />

</LinearLayout>

리사이클러뷰에 들어갈 메뉴항목이다. 일단 메뉴이름만 넣어놨다.

 

5. MenuItem.kt

package gdsc.knu

data class MenuItem(
    val menu: String
)

메뉴이름만 넣어놓은 데이터클래스도 만들어준다.

이걸 메뉴아이템에 넣을 거다.

 

6. LookupActivity.kt

package gdsc.knu

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import gdsc.knu.api.getStore
import gdsc.knu.databinding.StoreLookupBinding

class LookupActivity : AppCompatActivity() {
    private var mBinding: StoreLookupBinding? = null
    private val binding get() = mBinding!!
    var menuList = arrayListOf<MenuItem>()
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)

        mBinding = StoreLookupBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val store = getStore(1)

        binding.title.text = store.name
        binding.description.text = store.description
        binding.tel.text = store.tel
        binding.address.text = store.address
        binding.tel.text = store.tel
        binding.category.text = store.category
        addData(store.menu)
        binding.mRecyclerView.adapter = MenuAdapter(menuList)
    }
    override fun onDestroy(){
        mBinding = null
        super.onDestroy()
    }
    fun addData(mlist:List<String>){
        for(i in mlist){
            menuList.add(MenuItem(i))
        }
    }
}

조회하는 화면과 연결시킬 코틀린파일이다!

뷰바인딩 썼고, store 변수에다 가짜데이터를 넣어주었다.

그후 store_lookup.xml의 각 항목에 store 데이터를 넣어주었다.

이때 menu는 리사이클러뷰이기 때문에, menuList라는 arrayList를 먼저 선언해놓고 그걸 집어넣었다.

addData 함수를 만들어 store의 String 배열 값을 채운 후 넣었다.

 

7. MenuAdapter.kt

package gdsc.knu

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import gdsc.knu.databinding.MenuItemBinding

class MenuAdapter (private val menuList: ArrayList<MenuItem>): RecyclerView.Adapter<MenuAdapter.ViewHolder>(){
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = MenuItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }


    override fun getItemCount(): Int {
        return menuList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = menuList[position]
        holder.bind(item)

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

        fun bind(item: MenuItem){
            binding.nameTv.text = item.menu
        }
    }
}

마지막으로 어댑터다.

어댑터에는 onCreateViewHolder, getItemCount, onBindViewHolder를 필수로 오버라이딩 해야 한다.

onCreateViewHolder에는 뷰바인딩을 이용해 menu_item.xml과 바인딩해주었다.

getItemCount는 리스트 크기를 반환시켰고

onBindViewHolder는 menuItem리스트의 각 항목을 내가 설정한 리사이클러뷰 항목에 넣어주는 건데, 이 설정을 ViewHolder에서 한다.

ViewHolder의 bind에서 menu_item.xml에 메뉴항목을 넣었다.

 

결과화면~

끝!

728x90

'TIL' 카테고리의 다른 글

#0718 [안드로이드][코틀린] 계산기 앱 만들기 - 1  (0) 2022.07.20
#0711 코루틴과 비동기처리  (0) 2022.07.18
#0622 프로그래머스 실패율  (0) 2022.06.22
#0616  (0) 2022.06.16
#0531 스위프트 옵셔널 바인딩, 외부 파라미터  (0) 2022.05.31
    밍비
    밍비

    티스토리툴바