I have five activities/screens that I would like to be able to swipe between, each has a different function but are interrelated hence the UI concept of swiping between each.
I have found many discussions around ViewPager and PagerAdapters etc. but cannot seem to find one where swiping switches between different activity screens.
Is this even possible? Could someone point me towards an example project of this with source code? Or show me how to adapt an existing tutorial to do what I wish?
Thanks so much, have a good one!
You can't use ViewPager
to swipe between Activities
. You need to convert each of you five Activities
into Fragments
, then combine everything in one FragmentActivity
with the Adapter
you use with ViewPager
.
Here's a link that goes into detail on converting your current Activities
info Fragments
.
This is the Fragment topic on the Android Developers website, it has a lot of useful info.
Here's another example (full source) that inflates TextViews
on each page.
Here's an example that I typed up:
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
of 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 an example of the layout you'd 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 Fragment
create a new class that extends Fragment
. The first two methods you'll want to override
are onActivityCreated
and onCreateView
.
Here's how you could do that:
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;
}
}