androidandroid-recyclerviewpagerslidingtabstripandroid-tv

Control focus order between ViewGroups with uncertain items


I have an Android TV layout likes the image below.

  1. A PagerSlidingTabStrip on the top, and the data are pulled from the server;
  2. A ViewPager with Fragments on the bottom, and each fragment has a horizontal RecyclerView.

Scenario:

When the first tab(tab0) gets focus, then press the D-pad in down->right direction, the item2 in the RecyclerView get focus which works as expected;

Then press the D-pad in up direction, the tab4 get focus, which follows the default focus search order.

Question:

My question is how to keep the tab0 (last focused tab) get focus instead of tab4.

I know we can define the behavior by specifying, for each View, which control should gain focus next with nextFocusUp, nextFocusUp, nextFocusLeft, nextFocusRight attributes. But how to control focus order between ViewGroup with uncertain items for my part.

enter image description here


Solution

  • I solved the problem finally, described as below:

    1. Keep a reference of last focused view in PagerSlidingTabStrip;
    2. Create a custom ViewGroup, which is the parent view of PagerSlidingTabStrip and ViewPager;
    3. Override the dispatchKeyEvent method in the ViewGroup :

      @Override
      public boolean dispatchKeyEvent(KeyEvent event) {
          if (shouldInterceptDownKeyEvent(event) || shouldInterceptUpKeyEvent(event)) {
              if (mTabs.getLastFocusedView() != null) {
                  mTabs.getLastFocusedView().requestFocus();
              }
              return true;
          }
          return super.dispatchKeyEvent(event);
      }