android - 使用伴奏滑动刷新

标签 android kotlin android-jetpack-compose jetpack-compose-accompanist

我正在使用伴奏库进行滑动刷新。 我采用了示例代码进行测试,但是,它不起作用。 我寻找采用它,但找不到。 我的代码有什么问题吗?

我想在用户需要刷新时滑动

class MyViewModel : ViewModel() {
    private val _isRefreshing = MutableStateFlow(false)

    val isRefreshing: StateFlow<Boolean>
        get() = _isRefreshing.asStateFlow()

    fun refresh() {
        // This doesn't handle multiple 'refreshing' tasks, don't use this
        viewModelScope.launch {
            // A fake 2 second 'refresh'
            _isRefreshing.emit(true)
            delay(2000)
            _isRefreshing.emit(false)
        }
    }
}

@Composable
fun SwipeRefreshSample() {
    val viewModel: MyViewModel = viewModel()
    val isRefreshing by viewModel.isRefreshing.collectAsState()

    SwipeRefresh(
        state = rememberSwipeRefreshState(isRefreshing),
        onRefresh = { viewModel.refresh() },
    ) {
        LazyColumn {
            items(30) { index ->
                // TODO: list items
            }
        }
    }
}


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContent {
            TestTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {



                }
            }
        }
    }
}

最佳答案

您的列表不占据全屏宽度,您应该包含状态参数:

SwipeRefresh(
    state = rememberSwipeRefreshState(isRefreshing),
    onRefresh = { viewModel.refresh() },
) {
    LazyColumn(state = rememberLazyListState(), modifier = Modifier.fillMaxSize()) {
        items(100) { index ->
            Text(index.toString())
        }
    }
}

或使用列:

Column(modifier = Modifier
    .fillMaxSize()
    .verticalScroll(rememberScrollState())) {
    repeat(100) { index ->
        Text(index.toString())
    }
}

关于android - 使用伴奏滑动刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70728061/

相关文章:

Android从json文件(.txt)获取数据

android - 协程中的范围混淆

android - Jetpack Compose wrapContentHeight/heightIn 在按钮周围添加了额外的空间

android - OutlinedTextField jetpack 在键盘后面组成

android - Adb 安装/上传 apk 需要很长时间

java - 不同行的 ListView 自定义适配器

java - 删除android应用程序的标题栏

file - 如何在kotlin中读取纯文本文件?

android - Kotlin/Android Studio错误:必需可编辑!找到了字符串?

kotlin - SnapshotStateList 如何检测发生了更改?