I have a registration form where I have a big condition to continue. For simplicity, I have an editText and a Button. I write with MVVM so I have a ViewModel() where
val stroke = MutableLiveData<String>()
is stored. So when stroke length is more than 5 the button has to be activated. I do it like this:
Activity
'class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
binding.setLifecycleOwner(this)
binding.model = viewModel
}}
View Model
class MainViewModel: ViewModel(){
val stroke = MutableLiveData<String>()
val enableButton = MutableLiveData<Boolean>()
get(){
field.value = (stroke.value ?: "").length > 5
return field
}}
xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="model"
type="nekono.inno.mvvmsample.MainViewModel"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="textPersonName"
android:text="@={model.stroke}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="49dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:enabled="@{model.enableButton}"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</android.support.constraint.ConstraintLayout>
</layout>
It seems like enabled only asks variable ones, at the moment of binding, after that it stops asking and holds the state that was at the moment of binding. How to fix this?
You could use a Transformations on stroke to achieve that.
val stroke = MutableLiveData<String>()
val enableButton: LiveData<Boolean> = Transformations.map(stroke) { it.length > 5 }
When stroke changes also the enableButton value will change
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With