I have 1 custom view that contains : TextView -> label ; EditText -> input ; TextView -> error message
I set the desired text on my EditText from my custom view using custom attribute
My binding adapter look like :
@InverseBindingMethods(InverseBindingMethod(type = CustImp::class,attribute = "customtext"))
class BindingAdapters {
companion object {
@JvmStatic
@BindingAdapter("customtext")
fun settextulmeui(editText: CustImp, text: String?) {
text?.let {
if (it != editText.nInput.text.toString()) {
editText.nInput.setText(it)
}
}
}
@JvmStatic
@BindingAdapter(value = ["customtextAttrChanged"], requireAll = false)
fun setListener(editText: CustImp, listener: InverseBindingListener?) {
if (listener != null) {
editText.nInput.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
}
override fun afterTextChanged(editable: Editable) {
listener.onChange()
}
})
}
}
@JvmStatic
@InverseBindingAdapter(attribute = "customtext")
fun gettextulmeui(nMe: CustImp): String {
return nMe.nInput.text.toString()
}
}
}
using in my layout like :
<CustImp
android:id="@+id/mTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customtext="@={login.mytext}"
/>
Using my observablefield "mytext" i can pre-populate my edittext from my customview. I can get any new value that was typed if i hit a submit button ( get the new value using my observablefield in my view model )
But : if i rotate the screen i lose all data;
Any help/clue? Thanks
While you say everything clears after rotating screen it seems you just creating your model object in onCreate
.
model = ModelClass()
Instead you should use ViewModelProviders
to get possibly existing instance.
protected fun onCreate(savedInstanceState: Bundle) {
...
model = ViewModelProviders.of(this).get(ModelClass::class.java);
//"this" must be Activity reference
}
But for that your ModelClass
must extend ViewModel
class and have empty constructor.
Of course, you can use onSaveInstanceState method to save models state, but for me ViewModel
is better.
P.S. Saying "model" I mean object called login
in your layout xml, that contains data for interface.