【发布时间】:2010-02-21 20:35:02
【问题描述】:
我已经尝试了Tab Layout example,并且我还修复了示例中的几个拼写错误(并将所有活动添加到清单中)。但是,当我在模拟器上运行它时,我在第一行得到一个 NullPointerException,上面写着
tabHost.addTab(spec);
所以我的问题当然是。导致此异常的示例有什么问题?我正在使用 Eclipse Galileo 并将目标包设置为 Android 1.5。到目前为止,我对 android 开发网站上的其他示例没有其他问题。
package com.example.hellotabwidget;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;
public class HelloTabWidget extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) throws RuntimeException {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
//final Context context = getApplicationContext();
intent = new Intent().setClass(this, ArtistsActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec); //******** NullPointerException after running this line
// Do the same for the other tabs
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SongsActivity.class);
spec = tabHost.newTabSpec("songs").setIndicator("Songs",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTabByTag("artists");
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
【问题讨论】:
-
没有提到
tabHost.setTab(spec);的行,主要是因为该示例中没有使用setTab()方法。事实上,我一般在 Android SDK 中都找不到。 -
糟糕,这是这篇文章的错字,不是我的代码。我更新了我的问题并发布了更多代码。
-
我后来重新审视了这个问题,发现它自己解决了。这一定是 SDK 中的一个错误,因为我在几个月后打开了该项目,它运行时没有任何问题。
-
我遇到了同样的问题 - 检查您的模拟器配置以及它是否附加到调试器。