I want to add in a fragment a tab with pagerview (scrollable).
public class MyFragment extends Fragment {
private FragmentTabHost tabHost;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
tabHost = new FragmentTabHost(getActivity());
tabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
tabHost.addTab(tabHost.newTabSpec("one").setIndicator("One"), OneFragment.class, null);
tabHost.addTab(tabHost.newTabSpec("two").setIndicator("Two"), TwoFragment.class, null);
return tabHost;
}
@Override
public void onDestroyView(){
super.onDestroyView();
tabHost=null;
}
}
With this layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
I tried several solutions, but do not work. I need to use fragment, not fragmentActivity. The code written up work.
Used xml file like this:
and your java file is here:
after that viewpager adapter is like this:
Small Code for Tablayout + ViewPager
XML layout
Note If you are not using AndroidX yet, you need to change following in layout.
com.google.android.material.tabs.TabLayout
toandroid.support.design.widget.TabLayout
androidx.viewpager.widget.ViewPager
toandroid.support.v4.view.ViewPager
But I'll strongly recommend to migrate to AndroidX, see @this answer to understand why.
And this is common
ViewPagerAdapter
for all your Viewpager in app.If you need to set
ViewPager
in Fragment, please check @this answer.