Joe*_*oel 12 android nullpointerexception android-tabhost
这是我的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
[...]
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)
[...]
Run Code Online (Sandbox Code Playgroud)
我需要通过代码执行此操作,我不能使用XML.任何人都可以帮我解决这个问题吗?
rec*_*que 44
对于可能想知道TabActivity被弃用的人,文档说您需要在添加选项卡之前调用setup(),而不使用TabActivity.
tabHost.setup();
Run Code Online (Sandbox Code Playgroud)
您应该使用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);
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
15958 次 |
| 最近记录: |