How to create multiple tab with different fragment / view - Android app

Most beginner android developer wonder how to create different fragment for each tab in their android app. Please follow this tutorial to create basic android app with 3 tab before continue with this tutorial. ( http://swengineercode.blogspot.com/2015/05/how-to-create-multiple-tab-on-android.html )

This example using android studio. Kindly download the studio here ( https://developer.android.com/sdk/index.html )

Step By Step 

1. Open "Three tab example" android app. ( Refer this tutorial to create "Three tab example" project )
2. Create New Fragment


























3. Give fragment name "FragmentOne"





















4. Repeat Step 2 to create next fragment. Give name for new fragment "FragmentTwo".
5.  Now you already have three tab application with 3 fragment. Next we need to link the fragment with the respective tab. Follow below code.

Table below show that each section in out tab that should we link.

TabFragment
Section 1fragment_main.xml
Section 2fragment_fragment_one.xml
Section 3fragment_fragment_two.xml














6. Open MainActivity.java class










7. Go to Fragment getItem(int position) method.

Image below is the original code

















Change the original code to this code

  @Override  
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch(position){
case 0 :
return PlaceholderFragment.newInstance(position + 1);
case 1:
FragmentOne fOne = new FragmentOne();
return fOne.newInstance("","");
case 2:
FragmentTwo fTwo = new FragmentTwo();
return fTwo.newInstance("","");
}
return PlaceholderFragment.newInstance(position + 1);
}

You will see the code with error like image below 



Do not worry. The code is not wrong. You just need to change the import class in FragmentOne and Fragment Two class. Refer Step below.

8. Goto FragmentOne class









9. Change import android.app.Fragment; to --> import android.support.v4.app.Fragment;















10. Repeat step 9 for FragmentTwo class.
11. Now you should not see the error again.





















12.  Last step need to do is to remove onAttach code for FragmentOne and FragmentTwo class. Refer image below.

Original Code
















After changed.















Complete. Now each tab has their own fragment.









Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example