android項目中碰到須要替換tabHost默認樣式的狀況,須要達到下圖的效果:
爲了作成這樣的效果,花了些時間,這裏作個筆記,給有須要的朋友。
步驟一:新建一個xml佈局文件,命名main.xml
<?
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"
android:background
="@color/white"
>
<
LinearLayout
android:orientation
="vertical"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
>
<
TabWidget
android:id
="@android:id/tabs"
android:layout_width
="fill_parent"
android:layout_height
="wrap_content"
android:gravity
="center_horizontal|center_vertical"
/>
<
FrameLayout
android:id
="@android:id/tabcontent"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
>
</
FrameLayout
>
</
LinearLayout
>
</
TabHost
>
步驟二:在Activity中添加咱們的tab
代碼以下
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = getTabHost();
Intent intent1 = new Intent(this,OfficialActivity.class);
createTab("公共聊天室",intent1);
Intent intent2 = new Intent(this, NearByActivity.class);
createTab("周邊",intent2);
Intent intent3= new Intent(this, HistoryActivity.class);
createTab("歷史",intent3);
mTabHost.setCurrentTab(1);
}
private void createTab(String text ,Intent intent){ mTabHost.addTab(mTabHost.newTabSpec(text).setIndicator(createTabView(text)).setContent(intent));
}
private View createTabView(String text) {
View view = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null);
TextView tv = (TextView) view.findViewById(R.id.tv_tab);
tv.setText(text);
return view;
}
步驟三:在createTabView方法中,咱們載入了佈局文件tab_indicator.xml,改佈局很簡單,就是放置一個帶背景的佈局,在佈局中放一個textView用於顯示tab標題,如下爲該佈局文件內容
<?
xml
version
="1.0"
encoding
="utf-8"
?>
<
LinearLayout
xmlns:android
="http://schemas.android.com/apk/res/android"
android:layout_height
="fill_parent"
android:layout_width
="fill_parent"
android:orientation
="vertical"
android:gravity
="center"
android:theme
="@android:style/Theme.NoTitleBar"
android:background
="@drawable/chat_tab_selector"
>
<
TextView
android:id
="@+id/tv_tab"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:text
="tab1"
android:textColor
="@color/white"
/>
</
LinearLayout
>
步驟四:在上面的佈局文件中咱們把該佈局的背景定義爲chat_tab_selector,這裏一樣須要在drawable文件夾下新建chat_tab_selector.xml,內容很簡單,就是作一個按下時的背景切換,內容以下:
<?
xml
version
="1.0"
encoding
="utf-8"
?>
<
selector xmlns:android = "http://schemas.android.com/apk/res/android"
>
<
item
android:state_focused = "true"
android:drawable = "@drawable/topbar_bg_down"
/>
<
item
android:state_selected = "true"
android:drawable = "@drawable/topbar_bg_down"
/>
<
item
android:state_pressed = "true"
android:drawable = "@drawable/topbar_bg_down"
/>
<
item android:drawable = "@drawable/topbar_background"
/>
</
selector
>
裏面作了兩張圖進行狀態切換,這兩張圖一樣放drawable下就能夠了 至此,自定義tab的步驟就完成了。若是要作成更復雜的樣式,你們能夠在此基礎上進行擴展。