Android TabHost.addTab – >空指针异常

前端之家收集整理的这篇文章主要介绍了Android TabHost.addTab – >空指针异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码
public class Main extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            TabHost tabHost = new TabHost(this);

            TabHost.TabSpec tab = tabHost.newTabSpec("tab1");
            tab.setIndicator("Tab 1");
            tab.setContent(new TabHost.TabContentFactory() {
                @Override
                public View createTabContent(String tag) {
                    TextView tv = new TextView(Main.this);
                    tv.setText("tab 1 content");
                    return tv;
                }
            });

            tabHost.addTab(tab);

            setContentView(tabHost);
        }
    }

我得到这个错误

[...]
    07-13 20:26:49.261: ERROR/AndroidRuntime(625): Caused by: java.lang.NullPointerException
    07-13 20:26:49.261: ERROR/AndroidRuntime(625):     at android.widget.TabHost.addTab(TabHost.java:206)
    07-13 20:26:49.261: ERROR/AndroidRuntime(625):     at test.test.Main.onCreate(Main.java:27)
    [...]

我需要通过代码来做,我不能使用XML.有人可以帮我修理这段代码吗?

解决方法

您应该使用TabActivity,它需要将相同的特殊布局设置为内容(请参阅 http://developer.android.com/resources/tutorials/views/hello-tabwidget.html).如果你不能使用xml,你应该从java代码构造相同的内容
public class Main extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TabHost tabHost = new TabHost(this);
    tabHost.setId(android.R.id.tabhost);

    TabWidget widget = new TabWidget(this);
    widget.setId(android.R.id.tabs);

    FrameLayout content = new FrameLayout(this);
    content.setId(android.R.id.tabcontent);

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(widget);
    layout.addView(content);

    tabHost.addView(layout);

    setContentView(tabHost);

    TabHost.TabSpec tab1 = tabHost.newTabSpec("tab1");
    tab1.setIndicator("Tab 1");
    tab1.setContent(new TabHost.TabContentFactory() {
        @Override
        public View createTabContent(String tag) {
            TextView tv = new TextView(Main.this);
            tv.setText("tab 1 content");
            return tv;
        }
    });

    tabHost.addTab(tab1);

    TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2");
    tab2.setIndicator("Tab 2");
    tab2.setContent(new TabHost.TabContentFactory() {
        @Override
        public View createTabContent(String tag) {
            TextView tv = new TextView(Main.this);
            tv.setText("tab 2 content");
            return tv;
        }
    });

    tabHost.addTab(tab2);

    setContentView(tabHost);
}

}

原文链接:https://www.f2er.com/android/312010.html

猜你在找的Android相关文章