布局文件的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="this is tab1" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="this is tab2"
android:id="@+id/et" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mylayout" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="tab3"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="this is tab3"
/>
</LinearLayout>
</LinearLayout>
主类的代码:
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();//实例分页菜单
//利用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.ic_launcher));
ts2.setContent(R.id.et);
ts3 = tableHost.newTabSpec("tabThree");
ts3.setIndicator("Tab3");
ts3.setContent(R.id.mylayout);//添加分页的布局
tableHost.addTab(ts1);
tableHost.addTab(ts2);
tableHost.addTab(ts3);
tableHost.setOnTabChangedListener(this);
//setContentView(R.layout.activity_main);
}
@Override
public void onTabChanged(String arg0) {
// TODO Auto-generated method stub
if(arg0.equals("tabOne"))
{
Toast.makeText(this, "分页1", Toast.LENGTH_LONG).show();
}
if(arg0.equals("tabTwo"))
{
Toast.makeText(this, "分页2", Toast.LENGTH_LONG).show();
}
if(arg0.equals("tabThree"))
{
Toast.makeText(this, "分页3", Toast.LENGTH_LONG).show();
}
}
}