Kyu-Ho Hwang
Kyu-Ho Hwang

Reputation: 183

swipe to refresh using accompanist

I'm using accompanist library for swipe to refresh. And I adopt it sample code for testing, however, it didn't work. I search for adopt it, but I couldn't find. Is there anything wrong in my code?

I want to swipe when user needs to refresh

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) {



                }
            }
        }
    }
}

Upvotes: 2

Views: 1743

Answers (1)

Johann
Johann

Reputation: 29885

Your list doesn't take up the full screen width and you should include the state parameter:

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

or with Column:

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

Upvotes: 2

Related Questions