MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = DataBindingUtil.setContentView(this,
R.layout.activity_main)
mainViewModel = ViewModelProviders.of(
this@MainActivity,
mainViewModelFactory
)[MainViewModel::class.java]
activityMainBinding.viewmodel = mainViewModel
activityMainBinding.lifecycleOwner = this
mainViewModel.fetchBusinessList()
mainViewModel.businessList.observe(this, Observer { items ->
run {
mainViewModel.isLoading.value = false
}
})
MainViewModel
class MainViewModel(val repository: MainActivityRepo) : ViewModel() {
val isLoading: MutableLiveData<Boolean> = MutableLiveData()
lateinit var businessList: LiveData<List<Content>>
fun fetchBusinessList() {
isLoading.value = true
businessList = repository.getBusinessList()
}
布局
<androidx.core.widget.ContentLoadingProgressBar
android:id="@+id/clp_fetching"
style="@style/Widget.AppCompat.ProgressBar"
android:layout_width="40dp"
android:layout_height="40dp"
android:visibility="@{viewmodel.isLoading?View.VISIBLE:View.GONE}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
我尝试过setValue
,postValue
并还添加了LifeCycleOwner
,这不会影响到false的可见性。
这里是一个观察结果
您已将isLoading声明为'val',这意味着它是只读的,无法更新。
val isLoading:MutableLiveData = MutableLiveData()
将其更改为
var isLoading:MutableLiveData = MutableLiveData()
术语是var声明了一个可变变量,而val声明了一个只读或一次分配的变量-因此这两种都称为变量。
关于ViewModel用户的更多观察结果
您正在尝试从活动中更新视图模型中的属性,但不应这样做。
查看模型
class MainViewModel(val repository: MainActivityRepo) : ViewModel() {
val isLoading: MutableLiveData<Boolean> = MutableLiveData()
lateinit var businessList: LiveData<List<Content>>
fun fetchBusinessList() {
isLoading.value = true
businessList = repository.getBusinessList()
}
// This is where you the content of the list would be received
fun onListUpdated(contentList : List<Content>){
businessList.value = contentList;
isLoading.value = false;
}
活动
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) mainViewModel = ViewModelProviders.of( this@MainActivity, mainViewModelFactory )[MainViewModel::class.java] activityMainBinding.viewmodel = mainViewModel activityMainBinding.lifecycleOwner = this mainViewModel.fetchBusinessList() mainViewModel.businessList.observe(this, Observer { items -> // Update UI Here })