老实说,我试过很多次,但都没有成功。
我在构造函数中有一个HomeViewModel
和一些数据:
class HomeViewModel(
val userName: MutableLiveData<String> = MutableLiveData(),
val userAvatar: MutableLiveData<String> = MutableLiveData(),
// ...
val showProgressBarUserInfo: MutableLiveData<Boolean> = MutableLiveData()
) : BaseViewModel() {
和函数saveUserInfo()
private fun saveUserInfo(user: User) {
showProgressBarUserInfo.value = true
getSomeOtherData()
showProgressBarUserInfo.value = false
}
其中函数getSomeOtherData()
还加载用户名和头像,它们也是绑定的
<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>
<import type="android.view.View" />
<variable
name="vm"
type="/path/to/HomeViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
// ...
android:visibility="@{vm.showProgressBarUserInfo ? View.VISIBLE : View.GONE}" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
我还尝试创建了一个函数setVisibleOrgOne()
(扩展与否)
fun View.setVisibleOrGone(bool: Boolean) {
if (bool) {
this.visibility = View.VISIBLE
} else {
this.visibility = View.GONE
}
}
使用@BindingAdapter(“showorhide”)注释,并像下面这样使用它
showOrHide="@{vm.showProgressBarUserInfo}"
但以上这些都不起作用。
附注。 用户名与头像得数据绑定成功,但未显示进度条。
P.S.S。 工具栏标题和ImageView:
app:title="@{vm.userName}"
loadAvatar="@{vm.userAvatar}"
其中LoadAvatar
是扩展函数
求求你,帮帮我
在我的情况下,当用户进入应用程序时,我加载一些数据,此时进度条应该是可见的。 我还使用了一个Koin,HomeViewModel是通过它初始化的,分别是变量showProgressBarUserInfo的默认值为“false”。 显然,在输入saveUserInfo()
函数时,GetSomeOtherData()
函数的调用执行得太快,以至于ProgressBar状态之间的切换是不可见的。
我解决了我的问题
init {
showProgressBarUserInfo.value = true
}
在我的HomeViewModel
顶部,使用
android:visibility="@{vm.showProgressBarUserInfo ? View.VISIBLE : View.GONE}"