Search code examples
androiddata-bindingandroid-databindingandroid-progressbarandroid-viewbinding

Android: How to bind ProgressBar visibility via DataBinding?


I've tried a lot, honestly, but without success.

I have a HomeViewModel and some data in constructor:

class HomeViewModel(
    val userName: MutableLiveData<String> = MutableLiveData(),
    val userAvatar: MutableLiveData<String> = MutableLiveData(),
    // ...
    val showProgressBarUserInfo: MutableLiveData<Boolean> = MutableLiveData()
) : BaseViewModel() {

and function saveUserInfo() in HomeViewModel

private fun saveUserInfo(user: User) {
    showProgressBarUserInfo.value = true
    getSomeOtherData()
    showProgressBarUserInfo.value = false
}

where function getSomeOtherData() also loads username and avatar, which are also binded

<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>

Also I've tried to create a function setVisibleOrGone() (extension or not)

fun View.setVisibleOrGone(bool: Boolean) {
    if (bool) {
        this.visibility = View.VISIBLE
    } else {
        this.visibility = View.GONE
    }
}

with @BindingAdapter("showOrHide") annotation and use it like

showOrHide="@{vm.showProgressBarUserInfo}"

but all of the above does not work.

P.S. data for username and avatar bind successfully, but progress bar is not showing.

P.S.S. Toolbar title and ImageView:

app:title="@{vm.userName}"
loadAvatar="@{vm.userAvatar}"

where loadAvatar is extension function

Please, help me


Solution

  • In my case, when the user enters the application, I load some data, and at this time the progress bar should be visible. I also use a Koin, and the HomeViewModel is initialized through it, respectively, the default value of the variable showProgressBarUserInfo is "false". Apparently, at the moment of entering the saveUserInfo() function, the call of the getSomeOtherData() function was performed so quickly that the switching between the states of the ProgressBar was invisible.

    I solved my problem by adding

    init {
        showProgressBarUserInfo.value = true
    }
    

    at the top of my HomeViewModel with

    android:visibility="@{vm.showProgressBarUserInfo ? View.VISIBLE : View.GONE}"