Android的TabHost.addTab - >空指针异常 [英] Android TabHost.addTab -> Null pointer exception
本文介绍了Android的TabHost.addTab - >空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的code:
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);
}
}
我得到这个错误:
I get this error:
[...]
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)
[...]
我需要code做到这一点,我不能使用XML。谁能帮我解决这个问题code吗?
I need to do this by code and I can't use XML. Can anyone help me fix this code please ?
推荐答案
您应该使用TabActivity,它需要相同的特殊布局设置为内容(见<一href="http://developer.android.com/resources/tutorials/views/hello-tabwidget.html">http://developer.android.com/resources/tutorials/views/hello-tabwidget.html).如果你不能使用XML,你应该建立在Java code相同的内容:
You should use TabActivity, it needs same special layout to be set as content (see http://developer.android.com/resources/tutorials/views/hello-tabwidget.html). If you can not use xml you should construct the same content from java code:
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);
}
}
这篇关于Android的TabHost.addTab - &GT;空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文