经过了一天的折腾, 在网上也找了不少源码, 但是效果都不是很好,非常长, 最后自己终于写出了一个代码不是很多的Tabhost。
先上图(背景是随便弄的, 所以不怎么样)
首先, 我们要先写一个主xml main.xml
每一个LinearLayout代表一个Tab内容
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:id="@+id/Tab1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是tab1"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/Tab2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是tab2"
/>
</LinearLayout>
</FrameLayout>
接下来是 tab样式的xml tab_style.xml
这里面添加了几张图片。
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:background = "@drawable/topbar_background"
>
<TextView android:id="@+id/tab_label"
android:layout_width="fill_parent"
android:layout_height="30px"
android:gravity="center"
android:textColor="#000000"
android:textStyle="bold"
android:background="@drawable/tab_bg"
/>
</RelativeLayout>
接下来就是tab 按下的状态 一个selector
这里topbar_bg_down是按下的图片
<?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"
/>
</selector>
最后是主 Activity的代码
public class MissedHelperActivity extends TabActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//取得当前的TabHost
TabHost tabs = getTabHost();
//载入主布局文件
LayoutInflater.from(this).inflate(R.layout.main, tabs.getTabContentView(), true);
//给Tab1添加自定义样式
RelativeLayout tabStyle1 = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_style, null);
TextView text1 = (TextView)tabStyle1.findViewById(R.id.tab_label);
text1.setText("1");
//给Tab2添加自定义样式
RelativeLayout tabStyle2 = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.tab_style, null);
TextView text2 = (TextView)tabStyle2.findViewById(R.id.tab_label);
text2.setText("2");
//创建新Tab, 使用tab1的样式
TabSpec tab1 = tabs.newTabSpec("tab1");
tab1.setIndicator(tabStyle1);
tab1.setContent(R.id.Tab1);
tabs.addTab(tab1);
//创建新Tab, 使用tab2的样式
TabSpec tab2 = tabs.newTabSpec("tab2");
tab2.setIndicator(tabStyle2);
tab2.setContent(R.id.Tab2);
tabs.addTab(tab2);
}
}
到这里就结束了, 代码里调用了几个图片, 这里就不放出来了。