How to implement a swipe feature with multiple fragments in Android
You will need a ViewPager and a FragmentPagerAdapter.
I’m assuming you have made your fragments for login and signup. Lets call them LoginFragment and SignupFragment.
- You can begin by making an activity say MainActivity with FrameLayout as its root element. Add a ViewPager in FrameLayout in activity layout xml.
Something like this -
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
2. Make a class that extends FragmentPagerAdapter and override getItem() method.
- public class MyAdapter extends FragmentPagerAdapter {
- ...
- // return the fragment according to swiped positon
- @Override
- public Fragment getItem(int position) {
- switch(position) {
- case 0:
- return LoginFragment.newInstance();
- case 1:
- return SignUpFragment.newInstance();
- }
- @Override
- public int getCount() {
- return 2;
- }
- ...
- }
3. Make an object of MyAdapter in your MainActivity and set the it as the adapter to the viewpager.
- // add this in onCreate of MainActivity
- ViewPager vp = (ViewPager) findViewById(...);
- MyAdapter myAdapter = new MyAdapter();
- vp.setAdapter(myAdapter);
Hope this helps.
Happy coding :)