我正在尝试在我的应用程序中使用TabHost实现Tabs,但我得到这个空指针异常。下面我有代码。任何人都可以帮助我。
final TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
final TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab");
final TabHost.TabSpec tab2 = tabHost.newTabSpec("Second Tab");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
tab1.setIndicator("Upcoming Matches").setContent(new Intent(this, ViewOtherExpense.class));
tab2.setIndicator("Recent Matches").setContent(new Intent(this, viewExpenseTypes.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.setup();
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#3399FF")); //selected
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#ADD6FF")); //unselected
//To change the Tab color
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#ADD6FF"));//unselected
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#3399FF")); // selected
}
});
答案 0 :(得分:1)
如果加载
setup()
正在使用TabHost
,则必须在添加标签之前致电findViewById()
。
所以我建议您在初始化之后和之前调用tabHost.setup();
之前添加tabHost.addTab()
final TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();