Method of android tv List Focus Memory

  • 2021-08-31 09:00:52
  • OfStack

In the development in Android tv, I often have to deal with the focus, A common requirement is to have focus memory function, The focus moves to an item 1 in the list, The focus moves out, and when it comes back, the focus should be located on the original project. For this requirement, the common implementation method is to implement the list with listview or recyclerview, maintain a variable to store the last focus position, and maintain this variable and use this variable to locate in the focus change or key-pressing event.

Concrete realization

For example, when the list is implemented with recyclerview, in each itemview keystroke event, whether the focus is moved outward is judged according to the keystroke direction and the position of the current view. If so, the focus mode of the parent view, that is, the recyclerview, is set, and the position information of the current view is saved

recyclerview.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

When the user moves back to the focus, because the focus mode is set to block in the previous step, the parent view will first obtain the focus and increase the event processing of focus change:


recyclerview.setOnFocusChangeListener(new OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
          Recyclerview recyclerview = (Recyclerview)v;
          recyclerView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
          if(mCurrentFocusPosition>0){
            LayoutManager layoutManager = recyclerView.getLayoutManager();
            View viewByPosition = layoutManager.findViewByPosition(mCurrentFocusPosition);
            if(viewByPosition!=null){
              viewByPosition.requestFocus();
            }
          }
        }
      }
    });

As shown in the code, in the focus change processing, setting the focus mode of view can make the sub view get the focus; Get the location information saved in the previous step to set the focus manually.

Another simpler method is introduced later, which has better encapsulation and does not need external logic to do maintenance processing.


Related articles: