如何解决在 EditText
我想在 editText 上使用双向数据绑定。 editText 的值来自我的 viewModel,属于 MutableLiveData 类型。
据我所知,实现双向绑定有很多不同的方法。我发现了很多使用 ObservableFields 的例子,但我不想使用它们,因为它们不知道生命周期。我还发现了在更新 EditText 后使用事件围绕 BindingAdapters 的示例
来自 C# WPF 我认为最好和最简单的方法是:
- 在 ViewModel 中使用 MutableLiveData
- 创建一个从“MutableLiveData”到 String 的 BindingAdapter,反之亦然
- 使用 BindingAdapter 将 ViewModel-Property 绑定到 EditText
我无法找到按照我想要的方式进行操作的示例。他们中的大多数看起来也很复杂
我找到的最详细的例子:
https://github.com/android/databinding-samples
https://github.com/enpassio/Databinding
https://developer.android.com/topic/libraries/data-binding
https://developer.android.com/codelabs/android-databinding#0
我的 Fragment 和 build.gradle 具有绑定所需的行(正常字符串绑定工作正常)。
另外请记住,我在这里发布的代码是我今天尝试过的许多不同方法的变体。我认为这个甚至不会编译。
我希望我能够展示我想要实现的目标,如果您能告诉我如何去做,我将不胜感激。
谢谢:)
<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="dashboardViewModel"
type="mp.ui.dashboard.DashboardViewModel" />
<variable
name="converter"
type="mp.ui.dashboard.Converter" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.dashboard.DashboardFragment">
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="145dp"
android:layout_height="44dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="@={converter.doubleToString(dashboardViewModel.waterPercentage)}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
class DashboardViewModel : ViewModel() {
val waterPercentage = MutableLiveData<Double>(60.0)
}
object Converter {
@InverseMethod("stringToDouble")
@JvmStatic fun doubleToString (view: EditText,double: MutableLiveData<Double>): String {
if(view.text.toString() != double.value.toString() ){
return double.value.toString()
}
return "0.0"
}
@JvmStatic fun stringToDouble(view: EditText,value: String): MutableLiveData<Double> {
if(view.text.toString() != null){
return MutableLiveData(view.text.toString().toDouble())
}
return MutableLiveData(0.0)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。