android基礎之TabSpec和TabHost

代碼如下:

佈局代碼:

wKioL1OmtniAH3IMAALCbsafnN8284.jpg

package com.example.tabhost;

import android.app.TabActivity;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.Menu;

import android.widget.TabHost;

import android.widget.TabHost.OnTabChangeListener;

import android.widget.TabHost.TabSpec;

import android.widget.Toast;


public class MainActivity extends TabActivity implements OnTabChangeListener {

private TabSpec ts1,ts2,ts3;//實例化3個分頁

private TabHost tableHost;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

tableHost=this.getTabHost();//實例化一個TableHost

//利用LayoutInflater將佈局與分頁菜單一起顯示

LayoutInflater.from(this).inflate(R.layout.activity_main, tableHost.getTabContentView());

ts1=tableHost.newTabSpec("tabOne");//實例化一個分頁

ts1.setIndicator("Tab1");//設置此分頁顯示的標題

ts1.setContent(R.id.btn);//設置此分頁的資源id

ts2=tableHost.newTabSpec("tabTwo");

//設置此分頁顯示的標題和圖標

ts2.setIndicator("Tab2",getResources().getDrawable(R.drawable.hagar3));

ts2.setContent(R.id.et);

ts3=tableHost.newTabSpec("TabThree");

ts3.setIndicator("tab3");

ts3.setContent(R.id.mylayout);//設置此分頁的佈局id

tableHost.addTab(ts1);//菜單中添加ts1分頁

tableHost.addTab(ts2);

tableHost.addTab(ts3);

tableHost.setOnTabChangedListener(this);

}

public void onTabChanged(String tabId)

{

if(tabId.equals("tabOne"))

{

Toast.makeText(this, "分頁1", Toast.LENGTH_LONG).show();

}

if(tabId.equals("tabTwo"))

{

Toast.makeText(this, "分頁2", Toast.LENGTH_LONG).show();

}

if(tabId.equals("tabThree"))

{

Toast.makeText(this, "分頁3", Toast.LENGTH_LONG).show();

}

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章