如何在片段中实现viewpager?

时间:2014-03-05 02:10:37

标签: android android-fragments android-viewpager

我一直在寻找并且很难找到明确的例子吗?我试图了解如何在我的mainActivity中作为抽屉项打开的片段中创建一个viewpager ......

这是我的尝试,但我认为我做错了,不管是我错误地包含它还是把它放在错误的位置......

public class RandomFragment extends android.app.Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_random, container, false);

        return rootView;
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ViewPager mViewPager = (ViewPager) view.findViewById(R.id.random_pager);
        mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    }

    public static class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public Fragment getItem(int position) {
            Bundle args = new Bundle();
            args.putInt(TextViewFragment.POSITION_KEY, position);
            return TextViewFragment.newInstance(args);
        }
}

1 个答案:

答案 0 :(得分:1)