/**
* Tab選項卡類似與電話本的界面,通過多個標籤切換不同的內容,要實現這個效果,首先要知道TabHost,
* 它是一個用來存放多個Tab標籤的容器,每一個Tab都可以對應自己的佈局,比如,電話本中的Tab佈局就
* 是一個線性佈局
* 要使用TabHost,首先要通過getTabHost方法獲取TabHost的對象,然後通過addTab方法來向
* TabHost中添加Tab,當然每個Tab在切換時都會產生一個事件,要捕捉這個事件,需要設置TabActivity
* 的事件監聽setOnTabChangedListener
*/
效果圖
發現很多微薄如騰訊,新浪的選項卡 都是顯示在頁面底部的,網上有資料:通過反射獲取tabwidget中的私有變量,改變其值。
<!-- 實現Tab標籤的居底主要是通過設置屬性 android:layout_weight="1" -->
<!-- 還要注意FrameLayout標籤的位置,要寫在TabWidget標籤的前面 -->
效果圖
本程序main.xml源碼
[html] view plaincopy
<?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">
<!-- 實現Tab標籤的居底主要是通過設置屬性 android:layout_weight="1" -->
<!-- 還要注意FrameLayout標籤的位置,要寫在TabWidget標籤的前面 -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<TabWidget
android:id="@android:id/tabs"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</TabHost>
java源碼
[html] view plaincopy
import android.app.TabActivity;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
public class TabWidgetActivity extends TabActivity
{
TabHost tabhost;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得TabHost對象
tabhost = getTabHost();
//爲TabHost添加標籤
//新建一個newTabSpec(newTabSpec)
//設置其標籤和圖標(setIndicator)
//設置內容(setContent)
tabhost.addTab(tabhost.newTabSpec("tab1")
.setIndicator("TAB 1",getResources().getDrawable(R.drawable.icon))
.setContent(R.id.text1));
tabhost.addTab(tabhost.newTabSpec("tab2")
.setIndicator("TAB 2",getResources().getDrawable(R.drawable.icon))
.setContent(R.id.text2));
tabhost.addTab(tabhost.newTabSpec("tab3")
.setIndicator("TAB 3",getResources().getDrawable(R.drawable.icon))
.setContent(R.id.text3));
//設置TabHost的背景顏色
//tabhost.setBackgroundColor(Color.argb(150,22,70,150));
//設置TabHost的背景圖片資源
tabhost.setBackgroundResource(R.drawable.bg0);
//設置當前顯示哪個標籤
tabhost.setCurrentTab(0);
//標籤切換事件處理,setOnTabChangedListener
tabhost.setOnTabChangedListener(new OnTabChangeListener()
{
public void onTabChanged(String tabId)
{
switch(tabhost.getCurrentTab())
{
case 0:
tabhost.setBackgroundResource(R.drawable.bg0);
Toast.makeText(getApplicationContext(), "當前標籤爲第一個頁面", Toast.LENGTH_SHORT).show();
break;
case 1:
tabhost.setBackgroundResource(R.drawable.bg1);
Toast.makeText(getApplicationContext(), "當前標籤爲第二個頁面", Toast.LENGTH_SHORT).show();
break;
case 2:
tabhost.setBackgroundResource(R.drawable.bg2);
Toast.makeText(getApplicationContext(), "當前標籤爲第三個頁面", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}