Hi guys, How can I use `BackHandler` in the proje...
# compose
k
Hi guys, How can I use
BackHandler
in the project? I am trying to use customise back handler in my project. I am trying to follow this answer, but it didn't work to go back in screen.
TopBar
Copy code
@Composable
fun TopBar(
    activity: ComponentActivity = (LocalContext.current as ComponentActivity),
    handleOnBackPressed: () -> Unit = { activity.finish() },
    content: @Composable (PaddingValues) -> Unit = {}
) {
    var isBackPressed by remember { mutableStateOf(false) }
    Scaffold(
        topBar = {
            TopAppBar(
                title = {},
                navigationIcon = {
                    IconButton(
                        onClick = { isBackPressed = true }
                    ) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = null,
                            tint = Aqua
                        )
                    }
                    if (isBackPressed) {
                        BackHandler(enabled = true, onBack = {
                            handleOnBackPressed()
                        })
                    }
                }
            )
        },
        content = content
    )
}
I am running this in Pixel 7 with Android 13. Using
compose_bom = "2022.11.00"
. Thanks
z
What do you want to achieve by this actually
k
I want to normal close the activity.
activity.onBackPressed()
is deprecated.
z
Simply call activity.finish() in onclick of navigation icon
k
It works, but what is the d/w
finish
and
BackHandler
?
z
BackHandler when user presses back button and you don't want to go back and you need to do some task. E.g when drawer is open so you pass condition in BackHandler argument that if deawer is opened then close it first and then in second press of back it goes back.
k
How can we do that, I have some condition like that..
z
I will share code
k
Thanks
z
Copy code
var state by remember { mutableStateOf("") }
    var textFocus by remember { mutableStateOf(false) }
    val focusManager = LocalFocusManager.current
    BackHandler(textFocus) { focusManager.clearFocus() }
    
    OutlinedTextField(
        value = state,
        onValueChange = { str -> state = str },
        modifier = Modifier.onFocusChanged { focusState -> textFocus = focusState.hasFocus }
    )
in this code when textField has focus, so when user presses the back button it will first clearFcous in BackHandler lambda then in second press of back button it goes back.