Skip to content

Focus Recipes

Observing child focus

Use this to react to a child getting focus:

1
2
3
4
5
6
7
8
recyclerView.addOnViewFocusedListener(object : OnViewFocusedListener {
    override fun onViewFocused(
        parent: RecyclerView.ViewHolder,
        child: View,
    ) {
        // Child is now focused
    }
})

Note

If you set this in a vertical RecyclerView that contains multiple horizontal RecyclerViews, the parent will also receive this callback

Disabling focus changes

You might want to temporarily disable focus changes and prevent other views from being selected by the user:

recyclerView.setFocusSearchDisabled(true)

This will block focus requests coming from DPAD events.

Grid circular focus

Circular focus

Dispatches focus back to the opposite span when it is currently at an edge.

recyclerView.setFocusableDirection(FocusableDirection.CIRCULAR)

Grid continuous focus

Continuous focus

Dispatches focus to the next or previous positions.

recyclerView.setFocusableDirection(FocusableDirection.CONTINUOUS)

Preventing focus losses

You might want your DpadRecyclerView to keep focus if the user presses a DPAD event that would trigger a focus change to an outside view. This typically happens when the selection is at the first or last item.

Main direction

To prevent focus leaving from the main direction of scrolling, use setFocusOutAllowed:

recyclerView.setFocusOutAllowed(throughFront = true, throughBack = false)

Let's assume this RecyclerView has vertical orientation. The example above would allow focusing out when the first item is selected and KEYCODE_DPAD_UP is pressed, but it would prevent focus from leaving when the last item is selected and KEYCODE_DPAD_DOWN is pressed.

Secondary direction

To prevent focus leaving from the secondary direction of scrolling, use setFocusOutSideAllowed:

recyclerView.setFocusOutSideAllowed(throughFront = true, throughBack = false)

Let's again assume this RecyclerView has vertical orientation. The example above would allow focusing out when focus is at the first span and KEYCODE_DPAD_LEFT is pressed, but it would prevent focus from leaving when the last span is selected and KEYCODE_DPAD_RIGHT is pressed.