使用viewpager打开片段时设置片段标记

时间:2014-12-11 16:32:59

标签: android fragment

这是我的代码的一部分:

public class MenuExpenses extends Fragment {

    private ViewPager viewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.expenses,container, false);
        viewPager = (ViewPager) root.findViewById(R.id.pager);
        viewPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));

        // Bind the tabs to the ViewPager
        PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) root.findViewById(R.id.tabs);
        tabs.setViewPager(viewPager);
        return root;
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        private final String[] TITLES = { "Daily", "Recurring" };

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {

                case 0: return new MenuExpensesDaily();
                case 1: return new IncomeList2();
                default: return new MenuExpensesDaily();
            }
        }
    }
}

MenuExpensesDaily& IncomeList2都是片段。那么如何在这里为它们设置片段标签呢?

1 个答案:

答案 0 :(得分:0)

您可以覆盖instantiateItem方法,将片段保存到SparseArray / HashMap,然后创建一个方法以返回带有位置的片段。现在,您将能够访问所选的片段并将标记设置为它。