Hide a tab in the TabHost in Android

江枫思渺然 提交于 2019-12-07 12:28:58

问题


if( ......)
    {


        tabHost.getTabWidget().getChildAt(0).setVisibility(View.GONE);
                    //to hide the first tab in the TabHost

    }

Is there anything wrong with this code ? The application crashes when I add this code inside the onCreate() method.. Any idea ?

My LogCat :

05-31 22:03:38.471: E/AndroidRuntime(598): Caused by: java.lang.NullPointerException 05-31 22:03:38.471: E/AndroidRuntime(598): at swayam.dev.mushtouch.MushTouchActivity.setVisibilityControls(MushTouchActivity.j‌​ava:75) 05-31 22:03:38.471: E/AndroidRuntime(598): at swayam.dev.mushtouch.MushTouchActivity.onCreate(MushTouchActivity.java:220) 05-31 22:03:38.471: E/AndroidRuntime(598): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 05-31 22:03:38.471: E/AndroidRuntime(598): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

Also tried this code. Still keeps crashing.

getTabHost().getTabWidget().removeViewAt(0);

回答1:


My response is going to be too long so ill put it in an answer.

So far you have

TabHost  tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.getTabWidget().getChildAt(0).setVisibility(View.GONE);

You are getting a NullPointerException, meaning that whenever you are using that line of code, you are trying to change something that doesn't exist on screen, or possibly something off screen.

Check your Import statement for R.

Below your package statement you should have the following:

import your.package.R;

and not

import android.R;

Once that is fixed, when you reference your tab host, use the following:

TabHost  tabHost = (TabHost)findViewById(R.id.tabhost);

If that doesnt work, make sure the tabhost is actually on the screen and that your not in a seperate activity.




回答2:


If you wanna hide Tab you should use:

getChildTabViewAt() instead of getChildAt()

so your code should looks like this:

  tabHost.getTabWidget().getChildTabViewAt(0).setVisibility(View.GONE);


来源:https://stackoverflow.com/questions/10837133/hide-a-tab-in-the-tabhost-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!