How to set active item in the Action Bar drop-down navigation?

前端 未结 5 1124
清歌不尽
清歌不尽 2020-12-13 00:23

I\'m trying to fix the issue with restarting activity on orientation changes.

I have an ActionBar with drop-down list navigation and after every rotatio

5条回答
  •  醉话见心
    2020-12-13 00:42

    I was also experiencing the same issue. Making a lot of research I found the solution here:

    http://mohitum.wordpress.com/tutorials/android/ -->under Tip 5.

    Implement OnPageChangeListener and in the onPageSelected(int position) call this method like this:

    @Override
    public void onPageSelected(int position) {
      mActionBar.setSelectedNavigationItem(position);
      selectInSpinnerIfPresent(position, true);
    }
    private void selectInSpinnerIfPresent(int position, boolean animate) {
      try {
        ActionBar actionBarView = mActionBar;
        Class actionBarViewClass = actionBarView.getClass();
        Field mTabScrollViewField = actionBarViewClass.getDeclaredField(“mTabScrollView”);
        mTabScrollViewField.setAccessible(true);
        Object mTabScrollView = mTabScrollViewField.get(actionBarView);
        if (mTabScrollView == null) {
          return;
        }
        Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField(“mTabSpinner”);
        mTabSpinnerField.setAccessible(true);
        Object mTabSpinner = mTabSpinnerField.get(mTabScrollView);
        if (mTabSpinner == null) {
          return;
        }
        Method setSelectionMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod(“setSelection”, Integer.TYPE, Boolean.TYPE);
        setSelectionMethod.invoke(mTabSpinner, position, animate);
        Method requestLayoutMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod(“requestLayout”);
        requestLayoutMethod.invoke(mTabSpinner);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    

    I hope this may help someone else too.

提交回复
热议问题