BindingAdapter)플래그먼트_recyclerView

소정·2023년 5월 26일
0

Kotlin

목록 보기
16/27
post-thumbnail
  • 프래그먼트에서 데이터 바인딩 or 기본 속성으로 지정이 불가한 data binding 대응
  • 기본 뷰에 없는 속성을 새롭게 만드는 문법

데이터 바인딩은 xml이 분리되어 있으면 다 가능하다

[1] 데이터 바인딩 whit 프래그먼트

  1. MVVM 패턴에서 View에서 사용할 데이터(model)을 연결해주는 ViewModel 역할의 클래스 정의
package com.bsj0420.ex97databinding

import androidx.databinding.ObservableField

//MVVM 패턴에서 View에서 사용할 데이터(model)을 연결해주는 ViewModel 역할의 클래스 정의
class MyDataViewModel {

    //이미지 뷰에서 보여줄 이미지 souce URL(문자열 경로)
    val img : ObservableField<String> = ObservableField("https://cdn.pixabay.com/photo/2016/03/23/15/00/ice-cream-1274894_1280.jpg")


}
  1. 엑티비티에 프래그먼트 화면 두기
  1. 프래그먼트 화면 준비

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

    <data>


    </data>


    <LinearLayout
        android:orientation="horizontal"
        android:padding="16dp"
        android:background="@color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <!-- 기본적인 data binding 학습으로 해결하기 어려운 문제 -->
        <!-- 1) 이미지 뷰 -->

        <!-- 2) 아답터 뷰 -->
        

    </LinearLayout>

</layout>
  1. 프래그먼트 화면 데이터바인딩 연결할 땐 DataBindingUtil.inflate

화면에서 할 작업들은 onViewCreated 콜백 함수에 쓴다

package com.bsj0420.ex97databinding

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.bsj0420.ex97databinding.databinding.FragmentMyBinding

class My_Fragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my, container, false)

        return binding.root
    }

    lateinit var binding : FragmentMyBinding

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //xml 레이아웃에서 사용할 데이터 클래스 객체를 생성 및 설정
        binding.vm = MyDataViewModel()

    }

}

[2] 데이터 바인딩 whit 리사이클러뷰

  • 플래그먼트 안에 리사이클러뷰 보여줌
<?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:tools="http://schemas.android.com/tools">

    <data>
        
        <variable
            name="vm"
            type="com.bsj0420.ex97databinding.MyDataViewModel" />

    </data>


    <LinearLayout
        android:orientation="horizontal"
        android:padding="16dp"
        android:background="@color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- 기본적인 data binding 학습으로 해결하기 어려운 문제 -->
        <!-- 1) 이미지 뷰 -->
        <!-- 이미지 경로가 대부분 서버의 URL인 경우가 많음 -->
        <!-- 이미지뷰의 src 속성은 res 폴더의 이미지만 설정 할 수 있다 - 그래서 이전엔 글라이더를 쓴것 -->
        <!-- 이미지 url을 설정하는 속성이 없음. 이를 해결하려면 새로운 속성을 만들어야함 -> 다음시간에...-->
        <ImageView
            android:src="@{vm.img}"
            android:background="@color/white"
            android:layout_margin="4dp"
            android:layout_width="180dp"
            android:layout_height="match_parent"/>

        <!-- 2) 아답터 뷰 [리사이크러 뷰] -->
        <!-- 대량의 데이터 리스트를 설정할 속성이 없음 => 이럴때 리스트값을 설정할 수 있는 속성을
        직접 만들어야함-->

        <!--  tools:listitem="@layout/recycler_item" 미리보기 속성 -->
        <androidx.recyclerview.widget.RecyclerView
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            android:orientation="vertical"
            android:background="@color/teal_700"
            android:layout_margin="4dp"
            tools:listitem="@layout/recycler_item"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <!-- 위 처럼 기본 뷰에 없는 속성을 새롭게 만드는 문법 : BindingAdapter 라고 부름 -->


    </LinearLayout>

</layout>

리사이클러 아이템

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:contentPadding="16dp"
    app:cardElevation="8dp"
    app:strokeWidth="2dp"
    app:strokeColor="@color/black">

    <TextView
        android:text="sample item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</com.google.android.material.card.MaterialCardView>

MyDataViewModel

  • 리사이클러가 보여줄 대량의 데이터 ViewModel에 준비
package com.bsj0420.ex97databinding

import androidx.databinding.ObservableField

//MVVM 패턴에서 View에서 사용할 데이터(model)을 연결해주는 ViewModel 역할의 클래스 정의
class MyDataViewModel {

    // 리사이클러뷰가 보여줄 사용할 대량의 데이터
    val items : ObservableField<MutableList<String>>  = ObservableField(mutableListOf())
    //초기값 = 빈 mutableListOf()


}
profile
보조기억장치

0개의 댓글