如何获取最后选择的操作栏选项卡?

时间:2015-01-05 09:27:48

标签: android android-actionbar

如何从最后选择的操作栏选项卡中导航到下一个选项卡?

我尝试了什么:

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        adapter = new FragmentPagerAdapter(getSupportFragmentManager(),
                title);

        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(adapter);
        viewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

                    /* (non-Javadoc)
                     * @see android.support.v4.view.ViewPager.SimpleOnPageChangeListener#onPageSelected(int)
                     */
                    @Override
                    public void onPageSelected(int position) {
                        // TODO Auto-generated method stub
                        actionBar.setSelectedNavigationItem(position);
                    }

                });

        for (int i = 0; i < adapter.getCount(); i++) {



            ActionBar.Tab tab = actionBar.newTab();

            tab.setText(adapter.getPageTitle(i));
            tab.setTabListener(this);
            actionBar.addTab(tab);

        }

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        viewPager.setCurrentItem(tab.getPosition());

        // here How Can I get previous selected tab from which I am navigating

        }

所以在onTabSelected()方法中如何知道我从哪个标签导航到此标签。是否有任何方法?

1 个答案:

答案 0 :(得分:2)

您可以创建一个名为

的字段
int fLastTab = -1;

您可以在onTabSelected函数

中更新此字段
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub
    viewPager.setCurrentItem(tab.getPosition());

    // Here you can check the value of fLastTab, 
    // if fLastTab == -1 there wasn't any last selected tab
    // and if it has another value you have the last selected tab
    // at the end of this function you will update the value of fLastTab

    // Doing somenthing with fLastTab....

    fLastTab = tab.getPosition();

}  

还有另一种方法,你可以覆盖函数

public void onTabUnselected(Tab tab, FragmentTransaction ft){

    // Doing somenthing with the last selected action bar tab (tab.position())...

}

您具有退出所选状态的选项卡的位置。 onTabUnselected