How to show selected fragment in action bar tab

后端 未结 1 1372
天涯浪人
天涯浪人 2020-12-09 07:05

I am facing one issue regarding tab swipe. My project is built on Android 3.2. I am implementing tab swipe using support library 4.0 (android-support-v4.jar). Everything imp

相关标签:
1条回答
  • 2020-12-09 07:32

    Problem: Due to an insufficient real-state the platform uses collapsed navigation (i.e. Spinner). The system auto-determines NAVIGATION_MODE_TABS for landscape & NAVIGATION_MODE_LIST for portrait, changing the orientation from landscape to portrait updates the UI but for some reason does not update the navigation mode property to NAVIGATION_MODE_LIST and hence mActionView.setDropdownSelectedPosition(position) is not called. See the following code of ActionBarImpl : setSelectedNavigationItem

        public void setSelectedNavigationItem(int position) {
        switch (mActionView.getNavigationMode()) {
        case NAVIGATION_MODE_TABS:
            selectTab(mTabs.get(position));
            break;
        case NAVIGATION_MODE_LIST:
            mActionView.setDropdownSelectedPosition(position);
            break;
        default:
            throw new IllegalStateException(
                    "setSelectedNavigationIndex not valid for current navigation mode");
        }
    }
    

    Workaround solution: Through reflection we can get the tab spinner object and call setSelection method.

    private Spinner getTabSpinner()
    {
        try
        {
            int id = getResources().getIdentifier("action_bar", "id", "android");
            View actionBarView = findViewById(id);
    
            Class<?> actionBarViewClass = actionBarView.getClass();
            Field mTabScrollViewField = actionBarViewClass.getDeclaredField("mTabScrollView");
            mTabScrollViewField.setAccessible(true);
    
            Object mTabScrollView = mTabScrollViewField.get(actionBarView);
            if (mTabScrollView == null) {
                return null;
            }
    
            Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField("mTabSpinner");
            mTabSpinnerField.setAccessible(true);
    
            Object mTabSpinner = mTabSpinnerField.get(mTabScrollView);
            if (mTabSpinner != null)
            {
                return (Spinner)mTabSpinner;
            }
        } 
        catch (Exception e) {
            return null;
        }
    
        return null;
    }
    

    Then call the above method in onPageSelected event.

            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
                Spinner spinner = getTabSpinner();
                if (spinner != null) {
                    spinner.setSelection(position);
                }
            }
    

    Referred this post https://gist.github.com/2657485

    0 讨论(0)
提交回复
热议问题