androidkotlindata-bindingkotlin-multiplatform2-way-object-databinding

How to properly use two way binding in Kotlin-Multiplatform?


I'm trying to use a String variable to bind it into my view. When I use a model object with a String property, it works well. But if I use the String variable alone, it only works with one way binding.

ViewModel:

class SampleModel(var data : String = "")

var myModel : SampleModel = SampleModel()
var myVariable : String = ""

XML:

<data>
   <variable
        name="model"
        type="MyViewModel.SampleModel" />

   <variable
        name="variable"
        type="String" />
</data>

<!-- Two way works fine -->
<EditText
    android:text="@={model.data}"/>


<!-- Only one way works -->
<EditText
    android:text="@={variable}"/>

The string in the SampleModel works well with two way binding but the String variable does not.

I think it is because the imported String in xml is java.lang.String but the String in the model is kotlin.String. And I'm unable to use the kotlin.String in xml.

Is there any solution to fix this? Or is there any proper way of two way binding in Kotlin-Multiplatform projects?


Solution

  • It looks like you have added a wrong variable in the xml file. In your view model you have created a variable named myVariable of type String but in your xml file you are creating one more variable here :-

     <variable
        name="variable"
        type="String" />
    

    so these both variables are different. You don't need to import anything in your xml file just create a viewModel variable which you have already done here :-

    <variable
        name="model"
        type="MyViewModel.SampleModel" />
    

    and now simply use this like :- android:text="@={model. myVariable}"

    UPDATE :- Here in this you need to use the String variable which i created in your viewModel because it used kotlin.String and in xml you have java.lang.String. You can simply use the variable which is created in your viewModel For eg :- android:text="@={viewModel.yourVariable}"