Android 2.1 NullPointerException with TabWidgets

时光毁灭记忆、已成空白 提交于 2019-11-30 23:05:54
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");

Are you allowed to use the same 'tag' for more than one TabSpec? I'd try setting those correctly and see if it fixes it.

EDIT: OK, so my suggestion didn't fix it but it makes sense to have unique tags anyway.

Try this to see if it helps. Add an option to set the currently selected tab at the end of your LoadLayout() method like so (see last line)...

/* Add tabSpec to the TabHost to display. */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
tabHost.addTab(thirdTabSpec);

tabHost.setCurrentTab(0); // <== Add this

EDIT2: I found the TabWidget.java source and line 206 (where the NullPointerException occurs) is...

mBottomLeftStrip.setState(selectedChild.getDrawableState());

...there are three possible causes of the exception that I can see.

  1. mBottonLeftStrip is null (highly unlikely)
  2. selectedCHild is null (TabWidget should default to child 0 and using tabHost.setCurrentTab() would have enforced that anyway)
  3. The result of selectedChild.getDrawableState() is null

The last seems to be the likely cause but I'm not sure what could cause it to return null.

Try Google for 'TabWidget.java source' - the second result points at grepcode.com which has line numbers and you can see what it's trying to do at the point of the exception.

Had the same problem with tabs populated from AsyncTask on 1.6 and 2.1. Looks like earlier versions doesn't like TabHost without any tabs. To solve it, I do not use TabActivity and create TabHost with all its hierarchy manually in onPostExecute function of AsyncTask.

An easy solution is to set the tabWidget visibility to gone in your layout

<TabWidget
    android:id="@android:id/tabs"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:visibility="gone" />

Then once you have defined your tabs content, you can make it visible again:

// Add tab content (here a fragment class)
tabHost.addTab(
    tabHost.newTabSpec("tag1").setIndicator("Title"), 
    contentFragment.class, 
    null);

// Set tabWidget visible again
tabWidget.setVisibility(View.VISIBLE);

Inspired by one of related TabHost answers:

public class FixedTabHost extends FragmentTabHost
{
    public FixedTabHost(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        try { super.dispatchDraw(canvas); }
        catch (Exception ignored) {}
    }
}

Worked for me.

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