我正在尝试在 oncreate 中使用此代码制作垂直选项卡
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid2");
firstTabSpec.setIndicator("First Tab Name").setContent(new Intent(this,PageOne.class));
secondTabSpec.setIndicator("Second Tab Name").setContent(new Intent(this,PageTwo.class));
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
}
public void tabHandler(View target){
//artistButton.setSelected(false);
// albumButton.setSelected(false);
//songButton.setSelected(false);
if(target.getId() == R.id.artist_id){
tabHost.setCurrentTab(0);
// artistButton.setSelected(true);
} else if(target.getId() == R.id.album_id){
tabHost.setCurrentTab(1);
// albumButton.setSelected(true);
} else if(target.getId() == R.id.song_id){
tabHost.setCurrentTab(2);
// songButton.setSelected(true);
}
}
这是 main.xml
<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">
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout android:layout_width="0dip"
android:layout_height="fill_parent" android:layout_weight="0.2">
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:id="@+id/artist_id"
android:onClick="tabHandler"/>
<Button android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:id="@+id/album_id"
android:onClick="tabHandler"/>
<Button android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:id="@+id/song_id"
android:onClick="tabHandler"/>
</LinearLayout>
</FrameLayout>
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="0dip"
android:layout_height="fill_parent" android:layout_weight="0.8"/>
但它在运行时抛出此异常
01-21 19:01:03.655: E/AndroidRuntime(1101): FATAL EXCEPTION: main
01-21 19:01:03.655: E/AndroidRuntime(1101): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleexample. .MainActivity}: java.lang.NullPointerException
添加这两行时: tabHost.addTab(firstTabSpec); tabHost.addTab(secondTabSpec);
但我不知道为什么