QNA > H > How To Implement A Swipe Feature With Multiple Fragments In Android

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.

  1. 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 -

  1. android:layout_width="match_parent"  
  2. android:layout_height="match_parent" >  
  3.  
  4. android:layout_width="match_parent"  
  5. android:layout_height="match_parent"/> 
  6.  
  7.  

2. Make a class that extends FragmentPagerAdapter and override getItem() method.

  1. public class MyAdapter extends FragmentPagerAdapter { 
  2. ... 
  3.  
  4. // return the fragment according to swiped positon 
  5. @Override 
  6. public Fragment getItem(int position) { 
  7. switch(position) { 
  8. case 0: 
  9. return LoginFragment.newInstance(); 
  10. case 1: 
  11. return SignUpFragment.newInstance(); 
  12.  
  13. @Override 
  14. public int getCount() { 
  15. return 2; 
  16.  
  17. ... 

3. Make an object of MyAdapter in your MainActivity and set the it as the adapter to the viewpager.

  1. // add this in onCreate of MainActivity 
  2. ViewPager vp = (ViewPager) findViewById(...); 
  3. MyAdapter myAdapter = new MyAdapter(); 
  4. vp.setAdapter(myAdapter); 

Hope this helps.

Happy coding :)

Di Fay Parry

Come aggiungere più colonne sonore a un video su un telefono Android :: Come la chirurgia plastica ha cambiato la tua vita?
Link utili