1

I have a lazy vertical grid, and the items are focusable, when the item is clicked it navigates to another screen, when the user presses the back button and comes back to the screen with lazy vertical grid, i want the item that was focused to get focus again. is it possible to even do this? i tried many different ways but i get the same error:

error: FocusRequester is not initialized. Here are some possible fixes:

   1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
   2. Did you forget to add a Modifier.focusRequester() ?
   3. Are you attempting to request focus during composition? Focus requests should be made in
   response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }

this is not the exact code i have, but its the same except some stylings:

        LazyVerticalGrid(columns = GridCells.Fixed(4)) {
            itemsIndexed(items = listOf(1,2,3,4,5)) { index, item ->
                val focusRequester = remember {
                    FocusRequester()
                }
                Column(
                    modifier = Modifier
                        .onFocusChanged {
                            // ...
                        }
                        .focusRequester(focusRequester)
                        .clickable {
                            // navigate to some page
                        }
                ) {
                    Text(text = item.toString())
                }
                if (item == 3) focusRequester.requestFocus()
            }
        }
DevineDecrypter
  • 151
  • 1
  • 16
  • Are you find any solution? – Binary May 18 '23 at 18:26
  • 1
    @Binary yeah, give the composable you want to focus a prop, like `focused = true`, then on the composable code make sure to check on render if the focused prop is true, and then use a FocusRequester() to set focus to it. – DevineDecrypter May 26 '23 at 06:03
  • @DevineDecrypter, I have been using similar implementation. Care to write it as a answer, instead of a comment? – arunkd13 Aug 21 '23 at 09:25

0 Answers0