首页 > 解决方案 > 如何在视图模型中使用 SwipeRefreshLayout?

问题描述

我正在 mvvm 中使用 SwipeRefreshLayout 进行开发。所以我在viewmodel和xml上写了代码。当我运行它时,进度条正在运行,但没有任何反应。日志不显示任何内容。请让我知道我应该解决什么问题。我使用了这个链接“ AndroidX SwipeRefreshLayout with DataBinding

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">
    <data>
        <variable
            name="viewmodel"
            type="com.haii.schedulemanager.schedule.ScheduleViewModel" />
    </data>


<FrameLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:refreshing="@{viewmodel.isLoading}"
        app:onRefreshListener="@{viewmodel::onRefresh}">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/scheduleListView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</FrameLayout>
</layout>

视图模型

class ScheduleViewModel @Inject constructor(
    private val scheduleRepository: ScheduleRepository
) : ViewModel() {


    private val _item = MutableLiveData<List<ScheduleItem>>()
    val item: LiveData<List<ScheduleItem>> = _item

    private val _oneSchedule = MutableLiveData<ScheduleItem>()
    val oneSchedule: LiveData<ScheduleItem> = _oneSchedule
    lateinit var mOneSchedule : ScheduleItem

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    fun getWeek(groupName : String){
        //_isLoading.value = false
        viewModelScope.launch {
            val itemList = scheduleRepository.getWeek(groupName)
            if(itemList.isEmpty()){
                Log.d("TAG","Null")
                _item.value=null
            }else{
                _item.value = itemList
            }
            //_isLoading.value = true
        }
    }

    fun onRefresh(){
        Log.d("TAG","onRefresh")
        getWeek("Haii")
    }
}

标签: android

解决方案


刷新页面时不要忘记清除列表。


推荐阅读