android中使用tab选项卡


android中使用tab选项卡。

1.继承TabActivity

2.布局文件中使用tabHost,tabWedgit和framework

3.在activity中通过源码添加tab选项卡,每个选项卡中显示指定activity中的内容。可以通过代码控制界面的显示效果。

public class MSN extends TabActivity{

 

public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.tab);//这里使用了上面创建的xml文件(Tab页面的布局)

   Resources res = getResources(); // Resource object to get Drawables

   final TabHost tabHost = getTabHost();  // The activity TabHost

   TabSpec spec;

   Intent intent;  // Reusable Intent for each tab

   final android.widget.TabWidget tabWidget = tabHost.getTabWidget();

   int height = 40;

   int width = 50;

 

 //第一个TAB

   intent = new Intent(this,MSNContactsList.class);//新建一个Intent用作Tab1显示的内容

   spec = tabHost.newTabSpec("好友列表")//新建一个 Tab

   .setIndicator("好友列表")//设置名称以及图标

   .setContent(intent);//设置显示的intent,这里的参数也可以是R.id.xxx

   tabHost.addTab(spec);//添加进tabHost

 

 

 //第二个TAB

   intent = new Intent(this,MSNChatting.class);//第二个Intent用作Tab1显示的内容

   spec = tabHost.newTabSpec("正在聊天")//新建一个 Tab

   .setIndicator("正在聊天")//设置名称以及图标

   .setContent(intent);//设置显示的intent,这里的参数也可以是R.id.xxx

   tabHost.addTab(spec);//添加进tabHost

 

tabHost.setCurrentTab(0); //设置当前的tab

 

for (int i =0; i < tabWidget.getChildCount(); i++) {

            //设置tab的高度、宽度

            tabWidget.getChildAt(i).getLayoutParams().height = height;

            tabWidget.getChildAt(i).getLayoutParams().width = width;

   }

 

 

 //当点击tab选项卡的时候,更改当前的背景

   tabHost.setOnTabChangedListener(new OnTabChangeListener(){

  @Override

  public void onTabChanged(String tabId) {

   // TODO Auto-generated method stub

   for (int i =0; i < tabWidget.getChildCount(); i++) {

    View v = tabWidget.getChildAt(i);

    if(tabHost.getCurrentTab()==i){

            v.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_lessblue));

            //更改tab标题颜色

            final TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);

            tv.setTextColor(getResources().getColorStateList(android.R.color.darker_gray));

    }

    else {

        v.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_blue));

        //更改tab标题颜色

            final TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);

            tv.setTextColor(getResources().getColorStateList(android.R.color.white));

    }

   }

  }});

 

 

 /**

         * 此方法是为了去掉系统默认的白色的底角

         * 

         * 在 TabWidget中mBottomLeftStrip、mBottomRightStrip

         * 都是私有变量,但是我们可以通过反射来获取

         * 

         * 由于还不知道Android 2.2的接口是怎么样的,现在先加个判断好一些

         */

   Field mBottomLeftStrip; 

        Field mBottomRightStrip; 

     if (Float.valueOf(Build.VERSION.RELEASE) <= 2.1) {

           try { 

              mBottomLeftStrip = tabWidget.getClass().getDeclaredField ("mBottomLeftStrip"); 

              mBottomRightStrip = tabWidget.getClass().getDeclaredField ("mBottomRightStrip"); 

              if(!mBottomLeftStrip.isAccessible()) { 

                mBottomLeftStrip.setAccessible(true); 

              } 

              if(!mBottomRightStrip.isAccessible()){ 

                mBottomRightStrip.setAccessible(true); 

              } 

             mBottomLeftStrip.set(tabWidget, getResources().getDrawable (R.drawable.tab_border1)); 

             mBottomRightStrip.set(tabWidget, getResources().getDrawable (R.drawable.tab_border1));         

           } catch (Exception e) { 

             e.printStackTrace(); 

           } 

     } 

 

}

 

}

布局文件tab.xml:

 

android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:layout_width="fill_parent" android:layout_height="wrap_content">

            android:id="@android:id/tabcontent"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:padding="5dp" />

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------

 

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.

  1. Start a new project named HelloTabWidget.
  2. First, create three separate Activity classes in your project: ArtistsActivityAlbumsActivity, and SongsActivity. These will each represent a separate tab. For now, make each one display a simple message using a TextView. For example:
    public 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);
       
    }
    }

    Notice that this doesn't use a layout file. Just create a TextView, give it some text and set that as the content. Duplicate this for each of the three activities, and add the corresponding  tags to the Android Manifest file.

  3. 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:

     

    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.)

    Now create a state-list drawable that specifies which image to use for each tab state:

    1. Save the icon images in your project res/drawable/ directory.
    2. Create a new XML file in res/drawable/ named ic_tab_artists.xml and insert the following:
      xml version="1.0" encoding="utf-8"?>
      xmlns:android="http://schemas.android.com/apk/res/android">
         

         
      android:drawable="@drawable/ic_tab_artists_grey"
               
      android:state_selected="true" />
         

         
      android:drawable="@drawable/ic_tab_artists_white" />

      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.

  4. Open the res/layout/main.xml file and insert the following:
    xml version="1.0" encoding="utf-8"?>
    xmlns:android="http://schemas.android.com/apk/res/android"
       
    android:id="@android:id/tabhost"
       
    android:layout_width="fill_parent"
       
    android:layout_height="fill_parent">
       

           
    android:orientation="vertical"
           
    android:layout_width="fill_parent"
           
    android:layout_height="fill_parent"
           
    android:padding="5dp">
           

               
    android:id="@android:id/tabs"
               
    android:layout_width="fill_parent"
               
    android:layout_height="wrap_content" />
           

               
    android:id="@android:id/tabcontent"
               
    android:layout_width="fill_parent"
               
    android:layout_height="fill_parent"
               
    android:padding="5dp" />
       

    This is the layout that will display the tabs and provide navigation between each Activity created above.

    The TabHost requires that a TabWidget and a FrameLayout both live somewhere within it. To position the TabWidget and FrameLayout vertically, a LinearLayout is used. The FrameLayout is where the content for each tab goes, which is empty now because the TabHost will automatically embed each Activity within it.

    Notice that the TabWidget and the FrameLayout elements have the IDs tabs and tabcontent, respectively. These names must be used so that the TabHost can retrieve references to each of them. It expects exactly these names.

  5. Now open HelloTabWidget.java and make it extend TabActivity:

     

    public class HelloTabWidget extends TabActivity {
  6. Use the following code for the onCreate() method:
    public 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);
    }

    This sets up each tab with their text and icon, and assigns each one an Activity.

    A reference to the TabHost is first captured with getTabHost(). Then, for each tab, a TabHost.TabSpec is created to define the tab properties. The newTabSpec(String) method creates a new TabHost.TabSpec identified by the given string tag. For each TabHost.TabSpec,setIndicator(CharSequence, Drawable) is called to set the text and icon for the tab, and setContent(Intent) is called to specify the Intent to open the appropriate Activity. Each TabHost.TabSpec is then added to the TabHost by calling addTab(TabHost.TabSpec).

    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 TabWidget object referenced. This is because a TabWidget must always be a child of a TabHost, which is what you use for almost all interaction with the tabs. So when a tab is added to the TabHost, it's automatically added to the child TabWidget.

  7. Now open the Android Manifest file and add the NoTitleBar theme to the HelloTabWidget's  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  tag should look like this:
     android:name=".HelloTabWidget" android:label="@string/app_name"
             
    android:theme="@android:style/Theme.NoTitleBar">
  8. Run the application.

Your application should look like this (though your icons may be different):

 

你可能感兴趣的:(android中使用tab选项卡)