I tried to add a tab with a fragment in my activity but it does not respond or event display.
Here is my code below.
This is my MAIN ACTIVITY:
private void setupTabLayout() {
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("COMMENTS"));
tabLayout.addTab(tabLayout.newTab().setText("ATTACHMENTS"));
tabLayout.addTab(tabLayout.newTab().setText("AUDIT TRAIL"));
tabLayout.addTab(tabLayout.newTab().setText("APPROVERS"));
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new com.example.android.ontrack.adapters.PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Here is my XML code:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/margin"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/margin"
android:paddingLeft="@dimen/padding"
android:paddingRight="@dimen/padding"
android:background="@color/blue"
android:fillViewport="true"
app:tabMode="scrollable"
app:tabIndicatorColor="@android:color/white"
app:tabSelectedTextColor="@android:color/white"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
And this is my PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int mNumOfTabs) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CommentsFragment tab1 = new CommentsFragment();
return tab1;
case 1:
AttachmentsFragment tab2 = new AttachmentsFragment();
return tab2;
case 2:
AuditTrailFragment tab3 = new AuditTrailFragment();
return tab3;
case 3:
ApproversFragment tab4 = new ApproversFragment();
return tab4;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}