You cannot use ViewPager
to scroll between Activities
. You need to convert each of you five Activities
into Fragments
, and then combine everything into one FragmentActivity
using the Adapter
that you use with ViewPager
.
Here's a link that details the conversion of current Activities
information to Fragments
.
This is a snippet of the topic on the Android developers website, it has a lot of useful information.
Here is another example (full source) that inflates TextViews
on every page.
Here is an example that I typed:
Pageradapter
public class PagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragments = new ArrayList<Fragment>(); public PagerAdapter(FragmentManager manager) { super(manager); } public void addFragment(Fragment fragment) { mFragments.add(fragment); notifyDataSetChanged(); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(position); } }
This should be called in onCreate
your FragmentActivity
:
private void initPaging() { FragmentOne fragmentOne = new FragmentOne(); FragmentTwo fragmentTwo= new FragmentTwo(); PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager()); pagerAdapter.addFragment(fragmentOne); pagerAdapter.addFragment(fragmentTwo); ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager); viewPager.setAdapter(pagerAdapter); }
This is a sample layout that you use for your FragmnetActivity
:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
To create a Fragment
, create a new class that extends Fragment
. The first two methods you want to use override
: onActivityCreated
and onCreateView
.
Here is how you could do it:
public class FragmentOne extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(THE_LAYOUT_FROM_YOUR_ORIGINAL_ACTIVITY, container, false); return view; } }