Why do I get a null pointer exception from TabWidget?

不想你离开。 提交于 2019-11-29 11:16:58

This does work for me:

tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("upcoming").setIndicator(
                getResources().getString(R.string.upcoming)).setContent(R.id.cell1));

Partial 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">
        <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">
            <include android:id="@+id/cell1"
                layout="@layout/my_layout_file" />
             <!-- another include for cell2, and the closing tags -->

For those of you who are using a TabHost not inside a TabActivity, then be sure to call TabHost.setup(). Here's the documentation for it: http://developer.android.com/reference/android/widget/TabHost.html#setup() Not doing so will result in a NullPointerException when you try to add tabs to your tabhost.

The tutorial fails to mention that, so I thought I'd bring it to your attention to save you guys the time I spent looking for it.

Nayden

Just wanted to provide some idea based on the statements from here:

http://code.google.com/p/android/issues/detail?id=14929

The TabWidget is causing a crash if you try to draw it before loading the data. To prevent this just use your async tasks/handlers not only to load the data but to set the content view too. Of course you could use some other view or progress dialog during the data loading process, just don't present the tabs holder yet.

YEAR! You need to call:

TabHost.setup()

before call the method. if not,the TabHost's TabWidget should be null. I made this mistake for so long.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!