[英]In Android, when swipe to change the screen how to show an animation with both screen
[英]How not to refresh screen when swipe
我正在开发一个应用程序,其中显示土豆列表,从 Firestore 检索数据。
我添加了一个滑动动作来刷新数据。 使用我在下面显示的代码,数据更新正常,调用 Firestore 并更新显示新值以防它们存在,或停止显示不再存在的值。
问题是当我滑动土豆列表屏幕时仍然是空白的,当对 Firestore 的调用结束时,它们会再次显示。 也就是说,屏幕会在几秒钟内变为空白。
有没有可能这不会发生? 这个效果有点丑
视图模型:
@HiltViewModel
class PotatoesViewModel @Inject constructor(
private val getPotatoesDataUseCase: GetPotatoesData
) : ViewModel() {
private val _state = mutableStateOf(PotatoesState())
val state: State<PotatoesState> = _state
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing: StateFlow<Boolean>
get() = _isRefreshing.asStateFlow()
init {
getPotatoes()
}
private fun getPotatoes() {
getPotatoesDataUseCase().onEach { result ->
when (result) {
is Resource.Success -> {
_state.value = PotatoesState(potatoes = result.data?.potatoes ?: emptyList())
}
is Resource.Error -> {
_state.value = PotatoesState(
error = result.message ?: "An unexpected error occurred"
)
}
is Resource.Loading -> {
_state.value = PotatoesState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
fun refresh() {
viewModelScope.launch {
_isRefreshing.emit(true)
getIncidents()
_isRefreshing.emit(false)
}
}
}
屏幕:
@Composable
fun PotatoesDataScreen(
navController: NavController,
viewModel: PotatoesViewModel = hiltViewModel()
) {
val state = viewModel.state.value
val isRefreshing by viewModel.isRefreshing.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
stringResource(R.string.app_name),
fontWeight = FontWeight.Bold
)
},
backgroundColor = Primary,
contentColor = Color.White
)
},
content = {
Box(modifier = Modifier.fillMaxSize()) {
SwipeRefresh(
state = rememberSwipeRefreshState(isRefreshing),
onRefresh = { viewModel.refresh() }
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(vertical = 8.dp)
) {
items(state.potatoes) { potato ->
PotatoCard(
potato = potato
)
}
}
}
}
}
)
}
马铃薯状态:
data class PotatoesState(
val isLoading: Boolean = false,
val potatoes: List<Potato> = emptyList(),
val error: String = ""
)
当列表屏幕为空白时,这是调用 Api 的时间。 当您拨打电话但仍未收到回复时,这也是列表为空白的情况。 每次您将PotatoesState
的新 Object 传递给mutableState
时:
Potatoes = emptyList()
)Potatoes = emptyList()
) UI 会根据您命名为_state
的MutableState
进行更新。
如果您想在收到新的响应之前保持相同的数据,那么您需要更新当前的state.value: MutableState<PotatoesState>
object 只有在您收到新的响应时(也称为is Resource.success
)。
或者,您可以实现一个加载微调器,并在您启动 Api 请求时显示它,直到isLoading
为false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.