(1)自定义Tab
通过tabHost的indicator来设置自己特殊的布局。
public class MainActivity extends TabActivity {
TabHost tabHost;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabHost = getTabHost();
setTabs();
tabHost.setCurrentTab(0);
}
private void setTabs() {
addTab("Home", R.drawable.tab_home, HomeActivity.class);
addTab("Chat", R.drawable.tab_chat, ChatActivity.class);
}
private void addTab(String labelId, int drawableId, Class<?> c) {
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(new Intent(this, c));
tabHost.addTab(spec);
}
}
主页面 res/layout/main.xml
把<TabWidget>放在<FrameLayout>的下边,让Tab导航处于屏幕底部
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
... >
<TabHost android:id="@android:id/tabhost" .. >
<LinearLayout .. >
<!-- 主体内容部分 -->
<FrameLayout android:id="@android:id/tabcontent" .. />
<!-- Tab导航部分 -->
<TabWidget android:id="@android:id/tabs" .. />
</LinearLayout>
</TabHost>
</RelativeLayout>
Tab布局 res/layout/tab_indicator.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
:
>
<ImageView android:id="@+id/icon" <-- ①
:
/>
<TextView android:id="@+id/title" <-- ②
:
android:textColor="@color/tab_text" <-- ③
/>
</RelativeLayout>
每个Tab的图标 res/drawable/tab_home.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="false" android:drawable="@drawable/home_normal"/>
<item android:state_selected="true" android:drawable="@drawable/home_selected" />
</selector>
Tab文字色 res/color/tab_text.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="false" android:color="#f888" />
<item android:state_selected="true" android:color="#ffff" />
</selector>
(2)做一个中间凸起的Tab
主页面 res/layout/main.xml
TabHost的下边添加
<ImageButton
android:id="@+id/ibHome"
android:layout_width="70sp"
android:layout_height="70sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@null"
android:src="@drawable/camera" />
MainActivity.java
ImageButton ib = (ImageButton) findViewById(R.id.ibHome);
ib.setOnClickListener(new OnClickListener() {
//...
});
在所有的Tab中间添加一个虚拟的Tab
addTab("", R.drawable.tab_home, HomeActivity.class);
最终效果图: