Search code examples
androidkotlinandroid-jetpack-compose

Handling back press in Jetpack Compose


I have a Composable which has different views (see the code for better understanding)
When user clicks on the button it navigates to different view but when user press the back button it navigates to previous screen but I want to navigate to pervious view
Something like on Back press viewState changes it's value
Note: I don't found nice explanation than this

var viewState by remember { mutableStateOf(0) }
    Column {
        when (viewState) {
            0 -> { Button(onClick = { viewState = 1 }) { Text(text = "Goto 1") } }
            1 -> { Button(onClick = { viewState = 2 }) { Text(text = "Goto 2") } }
            2 -> { Button(onClick = { viewState = 3 }) { Text(text = "Goto 3") } }
            3 -> { Button(onClick = { viewState = 4 }) { Text(text = "Goto 0") } }
        }
    }

Solution

  • I got the answer
    I have not added for 0 because it will execute navController

        var viewState by remember { mutableStateOf(0) }
        when(viewState){
            1 -> BackHandler(enabled = true) {
                viewState = 0
            }
            2 -> BackHandler(enabled = true) {
                viewState = 1
            }
            3 -> BackHandler(enabled = true) {
                viewState = 2
            }
        }
        Column {
            val nextViewState = (viewState + 1) % 4
            Button(onClick = { viewState = nextViewState }) {
                Text(text = "Goto $nextViewState")
            }
        }
    

    And the function

    EDIT: BackHandler is a system function