TabLayout tabLayout;
AppBarLayout appBarLayout;
ViewPager viewPager;
tabLayout = findViewById(R.id.tab_layout);
appBarLayout = findViewById(R.id.appBar);
viewPager = findViewById(R.id.pager);
ViewPagerAdapter adapter= new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new pendingTasks(), "Pending");
adapter.addFragment(new currentTasks(), "OnGoing");
adapter.addFragment(new completedTasks(), "Completed");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List < Fragment > fragmentList = new ArrayList < > ();
private final List < String > fragmentListTitles = new ArrayList < > ();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentListTitles.get(position);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentListTitles.add(title);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textColor="#ffffff"
android:text="TODO Tasks"
android:background="#424242"
android:textAppearance="@android:style/TextAppearance.Material.Widget.ActionBar.Title"
android:textSize="24sp" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="374dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/appBar"
app:layout_constraintVertical_bias="0.0"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="501dp"
tools:layout_editor_absoluteX="101dp"
tools:layout_editor_absoluteY="178dp" />
</LinearLayout>