Jetpack Compose 实现下滑刷新

引入依赖

首先引入google提供的依赖

    implementation 'com.google.accompanist:accompanist-swiperefresh:0.28.0'

MVI 的 ViewModel状态建设

这里就用Flow来实现观察者模式

class SwipeRefreshViewModel: ViewModel() {
    private val _isLoading = MutableStateFlow(false)
    val isLoading = _isLoading.asStateFlow()

    init{
        loadStuff()
    }
    fun loadStuff() {
        viewModelScope.launch{
            _isLoading.value = true
            delay(3000L)
            _isLoading.value = false
        }
    }

}

前端页面

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeRefreshTest(){
    //get the view model.
    val viewModel = ViewModelProvider(LocalContext.current as ViewModelStoreOwner)[SwipeRefreshViewModel::class.java]
    //tranverse it to state.
    val isLoading by viewModel.isLoading.collectAsState()
    //create PullRefreshState.
    val refreshState = rememberPullRefreshState(refreshing = isLoading, onRefresh = viewModel::loadStuff)
    //set the modifier to the Box.
    //in Box, set two Element, one is PullRefreshIndicator, another is the Layout you want to refresh or the RefreshLayout's component is traditional xml layout method.
    Box(modifier = Modifier.pullRefresh(refreshState, true)){
        PullRefreshIndicator(refreshing = isLoading, state = refreshState, modifier = Modifier.align(
            Alignment.TopCenter))
        LazyColumn(modifier = Modifier.fillMaxSize()){
            items(100){
                Text(text = "Test", modifier = Modifier
                    .fillMaxWidth()
                    .padding(32.dp))
            }
        }
    }
}

其实相当简单

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值