学习自android4.x手机/平板电脑程序设计入门,应用到精通一书
本文将Tab标签和Intent一起使用
在另一篇讲tabhost的博文中已经阐述了一种tabhost的使用方法,1.但那种方法的所有tab page都写在一个布局中,显的layout中的内容有点多,不易维护。2.实现的效果本文讲的和上一篇其实差不多。3.代码上是共通的,但是仍有不少地方已经变化了。4.所以总的来说,最好使用本文的方法,参考(一)中的内容,来加以比较理解。
1.写好activity_main.xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="70dp" >
</FrameLayout>
</TabHost>
2.写两个layout,再写两个activity。分别对应起来
3.MainActivity extends TabActivity
4.在MainActivity中写:
package com.tab2;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
Intent it = new Intent(MainActivity.this, One.class);
TabSpec spec1 = tabHost.newTabSpec("tab1");
spec1.setContent(it);
spec1.setIndicator("tab1",
getResources().getDrawable(android.R.drawable.alert_dark_frame));
tabHost.addTab(spec1);
it = new Intent(MainActivity.this, Two.class);
TabSpec spec2 = tabHost.newTabSpec("tab2");
spec2.setContent(it);
spec2.setIndicator("tab2",
getResources()
.getDrawable(android.R.drawable.alert_light_frame));
tabHost.addTab(spec2);
tabHost.setCurrentTab(0);
}
}
最后再把 <activity android:name="One"></activity>
<activity android:name="Two"></activity>
加入到AndroidManifest.xml中就好了
按下:tab1:
按下:tab2: