I'm reading many tutorial how to implement tabs in a class that extends FragmentActivity
,
but no one about how to implement tabs in a class that extends Fragment
I created with AndroidStudio a new project with a NavigationDrawerFragment
:
this navigationDrawerFragment for every option menu that it displays create a new Fragment. Inside this fragment i need to have some tabs.
how can i add tabs inside onCreateView
method of the fragment?
someone can give to me a very simple example?
What i'm doing to try to solve my problem:
Step 1 - i created a new LinearLayout
, it contains the tabHost
and it's the main fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment1"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TabHost
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabHost"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
Step 2 - on the main fragment I put this rows of code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.vediamo, container, false);
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
CreaAnnoFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
ModificaAnnoFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
EliminaAnnoFragment.class, null);
return mTabHost;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
If i run the program i get this error:
java.lang.NullPointerException at myapps.studentsmarks.CreaAnnoFragment.onAttach(CreaAnnoFragment.java:100)
FIXED - solution
"the wrapped fragment" don't need the onAttach()
method and this is logic. So just delete it