프로그래밍 공부/Android

[kotlin] LiveData & DataBinding

뚜벅이! 2021. 7. 20. 18:20
728x90

LiveData 가 나온뒤로 꽤 많은 시간이 흘렀다.

여러가지 문제점이 발견되었지만 자동으로 ui가 바뀌는 편함은 아직 따라올만한 대체재가 없을거같다.

프론트 프레임워크 vue가 각광받는 이유인듯.

 

 

ViewModel을 작성해주고 그 안에 MutableLiveData를 선언해준다.

class LiveDataModel : ViewModel() {

    private val _isUpdate = MutableLiveData<Title>()

    val isUpdate : LiveData<Title>
        get() = _isUpdate

    fun setText(text: Title){
        _isUpdate.value = text
    }
}

data class Title(
    var test_one: String? = null,
    var test_two: String? = null
)

isUpdate를 DataBinding 할거라서, get()을 집어넣어준다.

 

 

 

 

 

그다음 LiveData를 쓸 activity를 layout으로 묶어주어야한다.

<?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">

    <data>
        <variable
            name="LiveDataModel"
            type="com.test.model.LiveDataModel" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <LinearLayout
            android:id="@+id/ll_form"
            style="@style/LinearLayoutBase">

            <TextView
                android:id="@+id/text_test"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{LiveDataModel.isUpdate().test_one}"/>

            <FrameLayout
                android:id="@+id/fragment_test"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

android:text="@{LiveDataModel.isUpdate().test_one}"

이부분으로 LiveData의 값을 참조하도록 설정해준다

 

 

 

class TestActivity : AppCompatActivity() {

    private lateinit var binding: ActivityTestBinding
    private lateinit var viewModel : LiveDataModel

    companion object{
        private val TAG = TestActivity::class.java.simpleName
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_test)
        viewModel = ViewModelProvider(this).get(LiveDataModel::class.java)

        binding.apply {
            liveDataModel = viewModel
            lifecycleOwner = this@TestActivity
        }

        viewModel.isUpdate.observe(this, { it ->
            binding.text_test.text = it.test_one
        })
    }
}

setContentView로 binding될 layout을 같이 설정해주고,

viewModel을 가져온 후에 binding으로 해당 모델을 묶어준다.

 

그리고 observe로 설정해두면, 변화가 일어날때마다 UI가 변경될것이다.

 

viewModel = ViewModelProvider(requireActivity()).get(LiveDataModel::class.java)
val title = Title()
viewModel.setText(title.apply{ it.test_one = "hello" })

 

728x90