TabActivity in Android

Tabs can be created in Android, in a number of ways. I am going to create using Java only. I don't want to use xml and I want my tab content should be dynamic. So, I am implementing Tabs through TabHost.TabContentFactory. This interface has an abstract method called createTabContent() and it will return a View.

Another interesting fact , I came to know is, Tabs can be created without TabActivity too. Thats a new information for me. I came to know this through a discussion in Android Developers google group. If you are interested you can see the complete discussion here

The complete code for this is,


public class SampleTab extends Activity implements TabHost.TabContentFactory {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TabHost tabHost = new TabHost(SampleTab.this);
TabWidget tabW = new TabWidget(this);
FrameLayout frame = new FrameLayout(this);
frame.setId(android.R.id.tabcontent);
tabW.addView(frame);
tabW.setId(android.R.id.tabs);
tabHost.addView(tabW);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("Tab1").setIndicator("Tab1")
.setContent(this));
tabHost.addTab(tabHost.newTabSpec("Tab2").setIndicator("Tab2")
.setContent(this));
setContentView(tabHost);
}

public View createTabContent(String tag) {
TextView tv = new TextView(SampleTab.this);
tv.setText("This is from : " + tag);
return tv;
}
}


Happy Coding

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Open Gallery and get the selected image in appplication