Thursday, May 5, 2011

Dynamic Tabs

URL:http://android.attemptone.com/layouts/dynamic-tabs/

Dynamic Tabs

9 Nov 2010
Programmatically Created TabsTabs in android can be tricky to get right when you are creating them programmatically.  Here’s some code that will  give you a basic tab setup similar to the one at android developers.
Note: be sure that you use the given IDs in your TabHost, TabWidget, and FrameLayouts.
Other Note: The TabContentFactory class (PreExistingViewFactory)  needs to be used when creating tab content that does not use an existing view.  ie. when you are creating dynamic tab content.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;

//Dynamically Create Tabs
public class TabTest extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
setContentView(main);
TabHost tabs = new TabHost(this);
tabs.setId(android.R.id.tabhost);
main.addView(tabs);
TabWidget tabWidget = new TabWidget(this);
tabWidget.setId(android.R.id.tabs);
tabs.addView(tabWidget);
FrameLayout tabContent = new FrameLayout(this);
tabContent.setId(android.R.id.tabcontent);
tabContent.setPadding(0, 65, 0, 0);
tabs.addView(tabContent);
TextView content = new TextView(this);
content.setText("This is the Frame Content");
content.setId(100);
tabs.setup();
TabSpec tspec1 = tabs.newTabSpec("Tab1");
tspec1.setIndicator("One", this.getResources().getDrawable(android.R.drawable.star_on));
tspec1.setContent(new PreExistingViewFactory(content));
tabs.addTab(tspec1);
TabSpec tspec2 = tabs.newTabSpec("Tab2");
tspec2.setIndicator("Two", this.getResources().getDrawable(android.R.drawable.star_on));
tspec2.setContent(new PreExistingViewFactory(content));
tabs.addTab(tspec2);
TabSpec tspec3 = tabs.newTabSpec("Tab3");
tspec3.setIndicator("Three", this.getResources().getDrawable(android.R.drawable.star_on));
tspec3.setContent(new PreExistingViewFactory(content));
tabs.addTab(tspec3);
}
//Makes the content of a tab when it is selected.
class PreExistingViewFactory implements TabContentFactory{
private final View preExisting;
protected PreExistingViewFactory(View view){
preExisting = view;
}
public View createTabContent(String tag) {
return preExisting;
}
}
}

No comments:

Post a Comment