tabHost.setup() gives null pointer exception (Android studio)

前端 未结 2 1307
失恋的感觉
失恋的感觉 2021-01-16 16:17

I have a very simple app which is just an activity with a tab view on it.

I have initialised and casted everything to as it should be but am continually getting a nu

2条回答
  •  天命终不由人
    2021-01-16 16:55

    This Line shows that the TabHost you have created is in fragment_main.xml inside layout directory which is used by PlaceholderFragment

    tools:context="com.example.app.MainActivity$PlaceholderFragment"
    

    But you are finding your TabHost in activity_main.xml

    Move your code from onCreate() to onCreateView of PlaceholderFragment, below in same class if you are using default template comes with AS like

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
        TabHost tabHost = (TabHost) rootView.findViewById(R.id.tabHost);
        tabHost.setup();
    
        TabHost.TabSpec spec1, spec2, spec3;
    
        spec1 = tabHost.newTabSpec("spec1");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator("Tab1");
        tabHost.addTab(spec1);
    
        spec2 = tabHost.newTabSpec("spec2");
        spec2.setContent(R.id.tab2);
        spec2.setIndicator("Tab2");
        tabHost.addTab(spec2);
    
        spec3 = tabHost.newTabSpec("spec3");
        spec3.setContent(R.id.tab3);
        spec3.setIndicator("Tab3");
        tabHost.addTab(spec3);
    
       return rootView;
      }
    

    Or If you want you can move your TabHost to activity_main.xml as well without changing the java code but that is not recommended using fragments having a lot of benefits.

    Check this for benefits of using Fragments

    fragment_main and activity_main layouts in Android Studio

提交回复
热议问题