我的布局中有一个使用数据绑定的进度条。
<ProgressBar
android:id="@+id/pb_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/sov_avatar"
app:layout_constraintVertical_bias="0.32999998"
app:ui_state_loading="@{viewModel.UIState}"/>
绑定适配器是这样的
@BindingAdapter("ui_state_loading")
internal fun setUIStateForLoadingContent(view: View, repositoryResult: RepositoryResult<*>) {
Timber.tag("PROGRESS_BAR").d("binding adapter thread: ${Thread.currentThread().name}")
view.visibility = when (repositoryResult) {
is RepositoryResult.Loading -> View.VISIBLE
else -> View.INVISIBLE
}
}
绑定类是这样创建的。
_binding = FragmentRoutesBinding.inflate(layoutInflater, container, false).apply {
lifecycleOwner = this@RoutesFragment
viewModel = mViewModel
UIState是一个在我的ViewModel中创建的LiveData。
private val _UIState: MutableLiveData<RepositoryResult<CityData>> by lazy {
MutableLiveData<RepositoryResult<CityData>>().also {
it.value = RepositoryResult.Loading()
viewModelScope.launch {
val repositoryResult = withContext(Dispatchers.IO) {
mRepository.getCityData().run {
val cityData = this.data!!
routesFromJson = cityData.routes
poisFromJson = cityData.pointsOfInterest
// Code to get all the pois to copy in SearchSuggestionsContentProvider
/*val depoList = poisFromJson
var pois: String = ""
depoList?.forEach {
pois += "\"${it.name}\","
}
Timber.d(pois)*/
this
}
}
it.value = repositoryResult
}
}
}
override val UIState: LiveData<RepositoryResult<CityData>> = _UIState
现在,调试我的应用程序时,我看到绑定适配器方法被正确地调用了2次(都在主线程中),并且2个选项都被覆盖了(先是可见,然后是不可见,两者之间有几百毫秒的间隔),但ProgressBar在屏幕上仍然可见.我试着用ImageView替换ProgressBar,问题仍然存在.我不知道是什么原因。也许我改变可视性的速度太快了?
更新我用TextView试了一下:改变文字可以,改变可见性不行。
更新2我解决了改变View的alpha值的问题。但是我不知道为什么改变可见性属性不起作用。
使用 View.GONE
而不是 View.INVISIBLE
.