MVVM 绑定适配器未显示进度条



我正在尝试使用数据绑定和绑定适配器创建一个简单的示例,以便根据TextView显示/隐藏进度条是否为空。 下面你可以看到我的代码。我做错了什么?

loading_state.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="textString"
type="String"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:visibleGone="@{textString==null}">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{textString}"/>
</android.support.constraint.ConstraintLayout>
</layout>

我的绑定适配器

object BindingAdapters {
@JvmStatic
@BindingAdapter("visibleGone")
fun showHide(view: View, visible: Boolean){
view.visibility = if (visible) View.VISIBLE else View.GONE
}
}

我将布局包含在我的第二个片段中,以便检查文本视图文本

<include layout="@layout/loading_state"
app:textString="@{textView2.text.toString()}"/>

并且在我的 SecondFramgent 类中,我从 MainFragment 类中获取值(我正在使用新的导航组件(

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val txtFromMain = SecondFragmentArgs.fromBundle(arguments)
textView2.text = txtFromMain.txtFromMain
}

我错过了什么?

谢谢。

对于那些面临相同问题的人,您可以在下面找到我的解决方案匹配:

我不得不更改我的绑定适配器。

@BindingAdapter("visibleGone")
fun showHide(view: View, visible: String){
view.visibility = if (visible.isEmpty()) View.VISIBLE else View.GONE
}

您没有为 TV 设置双向数据绑定,因此字符串不会在数据绑定中更新

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{textString}"/>

android:text="@{textString}"更改为android:text="@={textString}"

这是问题的第一眼,有帮助吗?

最新更新