Is there a way to replace EditText
TextWatcher
with two way databinding pattern?
I tried:
class AddViewModel @Inject constructor() : ViewModel() {
val description = MutableLiveData<String>()
}
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/descriptionEditText"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="@dimen/default_spacing"
android:background="@drawable/ic_input_background"
android:gravity="top"
android:minHeight="200dp"
android:padding="4dp"
android:text="@{viewModel.description}"
app:layout_constraintBottom_toTopOf="@+id/postButton"
app:layout_constraintEnd_toEndOf="parent"/>
I found something similar here , but somehow I can't make it work.
UPDATE:
I was only missing =
sign after @
android:text="@{viewModel.description}"
-> android:text="@={viewModel.description}"
You should use OnTextChanged property in your XML
<data>
<variable
name="onTextChanged"
type="androidx.databinding.adapters.TextViewBindingAdapter.OnTextChanged" />
</data>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/descriptionEditText"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="@dimen/default_spacing"
android:background="@drawable/ic_input_background"
android:gravity="top"
android:minHeight="200dp"
android:padding="4dp"
android:onTextChanged="@{viewModel.description}"
app:layout_constraintBottom_toTopOf="@+id/postButton"
app:layout_constraintEnd_toEndOf="parent"/>
Now you can pass onTextChanged to included layout like below.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="@layout/base_edittext_view"
app:onTextChanged="@{(text, start, before, count) -> viewModel.onTextChanged(text)}"/>
</LinearLayout>
Then you need to add this method in your ViewModel
fun description(s: CharSequence,start: Int,before : Int,count :Int){
//TODO write your implementation here ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.