2016-03-31 12 views
0

Ich versuche Tabs mit TabHost in meiner App zu implementieren, aber ich bekomme diesen Null-Zeiger Ausnahme. unten habe ich den Code. Kann mir bitte jemand helfen.Versuch, die virtuelle Methode 'void android.widget.TabWidget.addView (android.view.View)' auf einem Nullobjekt Referenz

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

Aufruf Versuchen Aufruf 'tabHost.setup();' nach der Initialisierung. –

Antwort

1

Sie haben setup() aufrufen, bevor Registerkarten hinzufügen, wenn Laden TabHostfindViewById() verwendet wird. So

Ich schlage vor, Sie tabHost.setup(); nach der Initialisierung hinzufügen und vor tabHost.addTab() wie hier

final TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); 
tabHost.setup(); 
Verwandte Themen