Home > database >  BackHandler not exiting the appplication in Android Studio
BackHandler not exiting the appplication in Android Studio

Time:12-15

I am creating a notes application using JetPack Compose. I have a search bar at the top in which there is a BasicTextField where I put a Box and also BackHandler to exit the focus of the searchBar.

Here is the code:

@Composable
fun SearchBar(
    modifier: Modifier = Modifier,
    hint: String = "",
    onSearch: (String) -> Unit = {}
){
    var text by remember {
        mutableStateOf("")
    }
    var isHintDisplayed by remember {
        mutableStateOf(hint != "")
    }
    val focusManager = LocalFocusManager.current
    val myContext = LocalContext.current
    Box(modifier = Modifier){
        BasicTextField(
            value = text,
            onValueChange = {
                text = it
                onSearch(it)
            },
            maxLines = 1,
            singleLine = true,
            textStyle = TextStyle(color = Color.Black),
            modifier = Modifier
                .focusRequester(FocusRequester())
                .fillMaxWidth()
                .shadow(5.dp, shape = CircleShape)
                .background(Color.White, CircleShape)
                .padding(horizontal = 20.dp, vertical = 12.dp)
                .onFocusChanged {
                    isHintDisplayed = it.isFocused != true
                }
        )
        if(isHintDisplayed){
            Text(
                text = hint,
                color = Color.LightGray,
                modifier = Modifier
                    .padding(horizontal = 20.dp, vertical = 12.dp),
                fontSize = 18.sp,
                textAlign = TextAlign.Justify
            )
        }
        BackHandler(true) {
            focusManager.clearFocus()
        }
    }
}

Using the BackHandler, I am able to exit the focus of searchBar but on again pressing back my application is not exiting i.e. it remains on the same screen.

In oncreate function, I also tried using

onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })

but no use. Can anyone tell what's the problem ?

CodePudding user response:

The problem is you never disable BackHandler when focus has been cleared.

Create a variable with var focused by remember { mutableStateOf(false)}

Then update it inside Modifier.onFocusChanged { focused = it.isFocused}

 BackHandler(focused) {
            focusManager.clearFocus()
        }

now you will intercept back key only when focused is true

  • Related