How two ways databinding with a fragment works

135 views Asked by At

So, I've been using two ways databinding in my android apps and it's working well. By the way, I like to know cause of things. So my question is just to know how it works (I read many articles about two ways databinding but I'm still confused).

Bellow is an example of two ways databinding that I have implemented :

ViewModel:

class MainViewModel(...)...{
    val observable = Observer()

    class Observer:BaseObservable(){
        var post = Post(title = "", body = "")

        @Bindable
        fun getTitle(): String{
            return post.title
        }
        fun setTitle(title: String){
            if (post.title != title){
                post.title = title
                notifyPropertyChanged(BR.post)
            }
        }
    }
...

XML file:

    <data>
        <variable
            name="post"
            type="com.example.justbook.data.Post" />
    </data>
    ...
    <EditText
    ...
    android:text="@={post.title}" />

Fragment, in onCreateView():

        val post = Post(submitter_id = "")
        binding.lifecycleOwner = this
        binding.post = post
        ...
        binding.savePostButton.setOnClickListener{
                mainViewModel.observable.setTitle(post.title)
                ...
                // Do other actions with post variable

I guess the code is basic that you can understand without comment, but I add this just in case :

Here I want to save a post of a user.

  • In view model, I have a BaseObservable class that contains post and some setters and getters.
  • Then I have a XML file with two ways databinding syntax for setting title of the post.
  • And in fragment, all logics actions are done to save the post.

Is it first a good way of implementing it, even though it works ? Is there other ways I can do the same action ?

And, How does it work exactly ? If you can explain me role of each line, I will be very grateful :).

0

There are 0 answers