我正在尝试使用此代码制作垂直标签 在oncreate我尝试添加标签 并在tabHandler中单击一个按钮以设置要查看的选项卡
@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);
但我不知道为什么
答案 0 :(得分:1)
在此处输入代码您似乎使用android.R而不仅仅是R来访问您的资源。 android.R
访问不属于您的应用的Android资源,我假设您希望访问您创建的xml文件中的TabHost
。
tabHost = (TabHost)findViewById(android.R.id.tabhost);
应更改为:
tabHost = (TabHost)findViewById(R.id.tabhost);
答案 1 :(得分:1)
问题是扩展活动而不是扩展TabActivity