获取PagePageSlidingTabStrip页面标题onPageSelected

时间:2017-01-20 22:34:44

标签: android pagerslidingtabstrip

我试图从PagerSlidingTabStrip中获取所选页面标题以显示在吐司上。页面标题是从动态列表生成的。我可以使用以下方式在吐司上显示当前页面位置:

         tabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            Toast.makeText(getActivity(), "Page position: " + position, Toast.LENGTH_SHORT).show();


        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

如何获取当前/所选页面标题?

1 个答案:

答案 0 :(得分:0)

为PagerSlidingTabStrip创建自己的适配器(这是一个viewpager对吗?),它将管理标题和位置。

ViewPager viewPager;
ViewPagerAdapter vpAdapter;

在mainActivity中

viewPager = (ViewPager) findViewById(R.id.pager);
        vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), 2, this, clock, history);

<强> ViewPagerAdapter

public class ViewPagerAdapter extends FragmentPagerAdapter {
    private int nTabs;
    private Context context;
    private Fragment fragment1, fragment2;
    private CharSequence[] titles;

    public ViewPagerAdapter(FragmentManager fm, int nTabs, Context context, Fragment fragment1, Fragment fragment2) {
        super(fm);
        this.fragment1= fragment1;
        this.fragment2= fragment2;
        this.context =context;
        this.nTabs = nTabs;
        titles = new CharSequence[]{context.getText(R.string.Title_tab1), context.getText(R.string.Title_tab2)};
    }




    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return fragment1;
            case 1:
                return fragment2;
            default:
                return fragment1;
        }


    }


    @Override
    public int getCount() {
        return nTabs;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}

并且不要忘记在viewpager上设置适配器

viewPager.setAdapter(vpAdapter);