How do you rate this blog

Wednesday, November 30, 2011

Creation of Simple Tabs


                Well in some cases you wouldn’t want the forms to be segregated like Personal info, professional info. Well in such cases you can use tabs feature which makes the app appear more pleasant.
This post I have created a simple tab. Create a new project and open ‘main.xml’ file under layouts. Go to the graphical designer. On the Right hand side you see a pane called outline and you can see it has liner layout by default. So change this to tabhost, a tabhost is one which have various tab. You can see there are 3 tabs under tabhost, you can retain it as per your convenience but here I have retained only 2. The layout will look as shown below.



Now go to package under src folder and create 2 classes under it called activity1 and activity2 which will be called by the main file. Now open the main java file instead of extending Activity we will change it TabActivity. Then create a new tabhost and bind it to the default tabhost pre defined in android.
TabHost th=(TabHost) findViewById(android.R.id.tabhost);
Now we need to create 2 tabs and start activities in it. This is done as shown below
Creating new tabs
TabHost.TabSpec tab1=th.newTabSpec("tab1");
TabHost.TabSpec tab2=th.newTabSpec("tab2");
Creating new intents
tab1.setIndicator("My Activity1").setContent(new Intent(this,Activity1.class));
tab2.setIndicator("My Activity2").setContent(new Intent(this,Activity2.class));
Finally adding the tabs to tabhost on which it will be shown.       
th.addTab(tab1);
th.addTab(tab2);      
The main file will look like as shown below.


 
Now go to the Activity1 file and set the content to a textview. The file will look as shown below.



Similarly create Activity2 file.
Now that we are done defining layouts, actions and binding lets define activity in android manifest file by adding the code below inside application tag after the main activity tag.
<activity android:name=".Activity1"></activity>
<activity android:name=".Activity2"></activity>
 
Now run the application and you will see a screen as shown below.



Now click on other tab My Activity2 and you will see the output screen as shown below.



Well this was a simple one will try to showcase complex scenarios in future posts :).

No comments:

Post a Comment