Tab Layout
To create a tabbed UI, you need to use a TabHost and a TabWidget. The TabHost must be the root node for the layout, which contains both the TabWidget for displaying the tabs and a FrameLayout for displaying the tab content.
You can implement your tab content in one of two ways: use the tabs to swap Views within the same Activity, or use the tabs to change between entirely separate activities. Which method you want for your application will depend on your demands, but if each tab provides a distinct user activity, then it probably makes sense to use a separate Activity for each tab, so that you can better manage the application in discrete groups, rather than one massive application and layout.
In this tutorial, you'll create a tabbed UI that uses a separate Activity for each tab.
- Start a new project named HelloTabWidget.
- First, create three separate
Activityclasses in your project:ArtistsActivity,AlbumsActivity, andSongsActivity. These will each represent a separate tab. For now, make each one display a simple message using aTextView. For example:
Notice that this doesn't use a layout file. Just create apublic class ArtistsActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textview = new TextView(this); textview.setText("This is the Artists tab"); setContentView(textview); } }TextView, give it some text and set that as the content. Duplicate this for each of the three activities, and add the corresponding<activity/>tags to the Android Manifest file. - You need an icon for each of your tabs. For each icon, you should create two versions: one for when the tab is selected and one for when it is unselected. The general design recommendation is for the selected icon to be a dark color (grey), and the unselected icon to be a light color (white). (See the Icon Design Guidelines.) For example:
Now create a state-list drawable that specifies which image to use for each tab state:
- Save the icon images in your project
res/drawable/directory. - Create a new XML file in
res/drawable/namedic_tab_artists.xmland insert the following:
This is a state-list drawable, which you will apply as the tab image. When the tab state changes, the tab icon will automatically switch between the images defined here.<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- When selected, use grey --> <item android:drawable="@drawable/ic_tab_artists_grey" android:state_selected="true" /> <!-- When not selected, use white--> <item android:drawable="@drawable/ic_tab_artists_white" /> </selector>
- Save the icon images in your project
- For this tutorial, you can copy these images and use them for all three tabs. (When you create tabs in your own application, you should create customized tab icons.)
- Open the
res/layout/main.xmlfile and insert the following:
This is the layout that will display the tabs and provide navigation between each<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" /> </LinearLayout> </TabHost>Activitycreated above.Notice that theTabWidgetand theFrameLayoutelements have the IDstabsandtabcontent, respectively. These names must be used so that theTabHostcan retrieve references to each of them. It expects exactly these names. - The
TabHostrequires that aTabWidgetand aFrameLayoutboth live somewhere within it. To position theTabWidgetandFrameLayoutvertically, aLinearLayoutis used. TheFrameLayoutis where the content for each tab goes, which is empty now because theTabHostwill automatically embed eachActivitywithin it. - Now open
HelloTabWidget.javaand make it extendTabActivity: - public class HelloTabWidget extends TabActivity {
- Use the following code for the
onCreate()method:
This sets up each tab with their text and icon, and assigns each one anpublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, ArtistsActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("artists").setIndicator("Artists", res.getDrawable(R.drawable.ic_tab_artists)) .setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, AlbumsActivity.class); spec = tabHost.newTabSpec("albums").setIndicator("Albums", res.getDrawable(R.drawable.ic_tab_albums)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, SongsActivity.class); spec = tabHost.newTabSpec("songs").setIndicator("Songs", res.getDrawable(R.drawable.ic_tab_songs)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(2); }Activity.At the very end,setCurrentTab(int)opens the tab to be displayed by default, specified by the index position of the tab. - Notice that not once was the
TabWidgetobject referenced. This is because aTabWidgetmust always be a child of aTabHost, which is what you use for almost all interaction with the tabs. So when a tab is added to theTabHost, it's automatically added to the childTabWidget. - A reference to the
TabHostis first captured withgetTabHost(). Then, for each tab, aTabHost.TabSpecis created to define the tab properties. ThenewTabSpec(String)method creates a newTabHost.TabSpecidentified by the given string tag. For eachTabHost.TabSpec,setIndicator(CharSequence, Drawable)is called to set the text and icon for the tab, andsetContent(Intent)is called to specify theIntentto open the appropriateActivity. EachTabHost.TabSpecis then added to theTabHostby callingaddTab(TabHost.TabSpec). - Now open the Android Manifest file and add the
NoTitleBartheme to the HelloTabWidget's<activity>tag. This will remove the default application title from the top of the layout, leaving more space for the tabs, which effectively operate as their own titles. The<activity>tag should look like this:<activity android:name=".HelloTabWidget" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar"> - Run the application.
Your application should look like this (though your icons may be different):
References
'IT·디지털 > IT 개발자 팁' 카테고리의 다른 글
| 안드로이드 MediaPlayer 최신 사용법 정리(2025 ver.) (0) | 2011.02.17 |
|---|---|
| 안드로이드 화면 회전 방지 방법 (최신 버전 기준) (0) | 2011.02.16 |
| 추상클래스란 무엇인가: 개념부터 설계 철학까지 정리(2025년 업데이트) (0) | 2011.01.25 |
| IIS 64bitOS에서 32bit응용프로그램 실행하기 ODBC (1) | 2010.07.01 |
| IIS 64bitOS에서 32bit응용프로그램 실행 (0) | 2010.07.01 |