Reputation: 3657
I am attempting to create custom colors of the tabs in a TabHost.
I have impletmented OnTabChangeListener
and the MainActivity loads up correctly. However when I click on a new tab I get a null pointer. Where is my error located? I cannot understand what the issue is.
Here is the offending code loosely based off of this example
@Override
public void onTabChanged(String tabId) {
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundDrawable(getResources().getDrawable(R.drawable.greygradient));
}
tabHost.getTabWidget().getChildAt((tabHost.getCurrentTab())).setBackgroundDrawable(getResources().getDrawable(R.drawable.bluegradient));
}
Here is the trace:
06-20 14:27:42.770: E/AndroidRuntime(1490): java.lang.NullPointerException
06-20 14:27:42.770: E/AndroidRuntime(1490): at com.company.app.MainActivity.onTabChanged(MainActivity.java:72)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.widget.TabHost.invokeOnTabChangeListener(TabHost.java:359)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.widget.TabHost.setCurrentTab(TabHost.java:344)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:456)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.view.View.performClick(View.java:2485)
06-20 14:27:42.770: E/AndroidRuntime(1490): at android.view.View$PerformClick.run(View.java:9080)
Upvotes: 0
Views: 487
Reputation: 76536
You should have gone with the StackOverflow example: How do I change the background of an Android tab widget? :-)
@Override
public void onTabChanged(String tabId) {
setTabColor(getTabHost());
}
private void setTabColor(TabHost tabhost) {
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); //unselected
}
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
}
The most likely reason for your NullPointer is your TabHost, check that this is being instantiated, I assume you do it within onCreate.
If you are extending TabActivity you can just call getTabHost();
from your Activity context.
Upvotes: 1