How to handle back press on AndroidViewBinding & finish host compose?

Viewed 50

The composable host an AndroidView that is a FragmentContainerView which has multiple child Fragments on back press of the FragmentContainerView we want to close the @Game composable.

@Composable
fun Game(data: Bundle? = null) {

    val user = GamingHubAuthManager.getUser().observeAsState()

    AndroidViewBinding(EntryPointBinding::inflate) {
//        val myFragment = fragmentGameContainerView.getFragment<FeatureCardFragment>
    }

}
1 Answers

You can control if your Game composable is part of the composition from its parent composable with some state and a simple if statement.

To change the state on back press you can use the BackHandler composable.

A working example:

import androidx.compose.runtime.*

@Composable
fun GameParent() {
    var gameIsActive by remember { mutableStateOf(true) } // or false for the starting state

    BackHandler(enabled = gameIsActive) {
        gameIsActive = false
    }

    if (gameIsActive) {
        Game()
    } else {
        Button(
            onClick = { gameIsActive = true }
        ) {
            Text("Start game")
        }
    }
}

@Composable
fun Game(data: Bundle? = null) {
    val user = GamingHubAuthManager.getUser().observeAsState()

    AndroidViewBinding(EntryPointBinding::inflate) {
//        val myFragment = fragmentGameContainerView.getFragment<FeatureCardFragment>

    }
}

If you will have to close the game from some other handler(s) from inside the Game composable then taking this approach might be better

import androidx.compose.runtime.*

@Composable
fun GameParent() {
    var gameIsActive by remember { mutableStateOf(true) }  // or false for the starting state

    if (gameIsActive) {
        Game(onClose = { gameIsActive = false })
    } else {
        Button(
            onClick = { gameIsActive = true }
        ) {
            Text("Start game")
        }
    }
}

@Composable
fun Game(data: Bundle? = null, onClose: () -> Unit) {
    BackHandler(enabled = true) {
        // this way you can even pass some result back if you parametrize
        // this callback, for example won/lost/draw/quit.
        onClose()
    }
    
    val user = GamingHubAuthManager.getUser().observeAsState()

    AndroidViewBinding(EntryPointBinding::inflate) {
//        val myFragment = fragmentGameContainerView.getFragment<FeatureCardFragment>

        // call onClose() from some other handler
    }
}
Related