Search code examples
androidmvvmrobobinding

RoboBinding how does ViewModel know variable to return


Lets examine a simple example from here: Here is a simple layout file with a textview binding:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bind="http://robobinding.org/android">
<TextView
    bind:text="{hello}" />
    ...
<Button
    android:text="Say Hello"
    bind:onClick="sayHello"/>

and here is the view model for this layout:

 @org.robobinding.annotation.PresentationModel
public class PresentationModel implements HasPresentationModelChangeSupport {
    private String name;//how does framework now what to set name to ?
    public String getHello() {
        return name + ": hello Android MVVM(Presentation Model)!";
    }
    ...
    public void sayHello() {
        firePropertyChange("hello");
    }
}

my question is how does the viewModel know what name is ? it has not been set anywhere ? What if i had many variables like name2,name3 etc. how would it know what to bind ?


Solution

  • You should take a look to the entire source code

    MVVM example

    There is a getter and a setter in the presentation model class that manage the value of the name field with the two ways binding specified in the layout

            <EditText 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            bind:text="${name}"/>
    

    If you have more variables you must provide a getter and setter for each one if you want to use two way binding.