Fragment nested TabLayout and ViewPager

Table of Contents

Rendering:

Main page layout:

—Bottom navigationbottomnavigation–

menu.xml:

Click the navigation to jump to each Fragment:

Nested Tablayout + sub-Fragment + ViewPager in Fragment

Page Layout:

Summary of premise:

Components:

Linkage:

Idea:

New_Fragment + MainActivity.java source code:


The layout file is not released yet, the code file is for reference only

Rendering:

Main page layout:

//Clear, I drew it!

The creation of important menus is especially important

Right-click to create menu directory

Right-click to create menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@ + id/home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/home"
        android:title="x" />
    <item
        android:id="@ + id/news"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/news"
        android:title="x" />
    <item
        android:id="@ + id/profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:title="x"
        android:icon="@drawable/profile"/>
</menu>

As shown below:

First create three navigation bar fragments after jumping as shown in the figure

Fill in the layout file on the corresponding page and play freely

Click the bottom navigation bar to switch page binding fragments

 //Bottom navigation bar
        homeFragment = new Home_Fragment();
        newsFragment = new News_Fragment();
        profileFragment = new Profile_Fragment();
        

     //Lock the default main page
        settingdefaultfragment();

    //Click the bottom navigation bar to switch page binding fragments
        btnnavigationview = findViewById(R.id.btnnavigationview1);
        btnnavigationview.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                if(item.getItemId() == R.id.news){
                    fragmentTransaction.replace(R.id.framelayout,newsFragment);
                    // startActivity(new Intent(,NEW_fra.class));
                } else if (item.getItemId() == R.id.home) {
                    fragmentTransaction.replace(R.id.framelayout,homeFragment);
                } else if (item.getItemId() == R.id.profile) {
                    fragmentTransaction.replace(R.id.framelayout,profileFragment);
                }
                fragmentTransaction.commit();
                return true;
            }
        });

Lock the default page–settingdefaultfragment() function:

 public void settingdefaultfragment(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.framelayout,homeFragment);
        transaction.commit();
    }

Nested Tablayout + sub-Fragment + ViewPager in Fragment

Page layout:

Prerequisite summary:

Since the navigation bar has been built before, it is necessary to add the Tablayout and ViewPager components to the second parent fragment of the navigation bar. The previous Framlayout is where the fragments are placed, and the ViewPager is used to implement the pairing of children in the second parent fragment. The management of fragments is also a container for sub-fragments (that is to say, you no longer need to use Framllayout to load fragments), so as long as you implement the adapter creation of ViewPager and implement FragmentManager (fragment manager) in it, you can slide left and right to appear sub-fragments. If you want to There are components in sub-fragments, and components need to be created in the sub-fragment XML. How many pages do you want to slide left and right? Create as many sub-shards as you want. On the whole, it is a Fragment nested sub-fragment_list, which is managed by ViewPager and realizes page turning.

Please understand with the picture

Component:

Note, use viewpager to inherit view pager2

The component dragged in is still view pager2, but it is implemented using viewpager

Change the code from left to right

Add tabitem in the tablayout and create the corresponding Tab_fragment, which is the sub-fragment in NewFragment

Linkage:

Working environment: NewFragment [parent Fragment]

The NewFragment here is the Fragment of the main page, which is the second fragment that jumps out of the bottom navigation.

What we have to do is to link Tablayout with Viewpager

Linkage steps:1. Connect sub-fragments into a linked list

2. Create an adapter for viewpager, which is viewPager.setAdapter (getChildFragmentManager())

Rewrite the getitem(), getcount(), getPagetitle() methods //pagetitle is the tab tag (you can create a String array to store the tag name)

3.tabLayout.setupWithViewPager(viewPager2,false);

Idea:

Among them, getChildFragmentManager() requests the subclass FragmentManager(), and FragmentManager() will automatically manage Fragmennt, so create an adapter and pass in the FragmentManage object, which basically completes the setting of the viewpager. If tablayout is not needed, the last step is not done, and each Just create the corresponding imageview and textview components in the sub-Fragment.

New_Fragment + MainActivity.java source code:

New_Fragment source code:

public class News_Fragment extends Fragment {

    private TabLayout tabLayout;
    private ViewPager viewPager2;
    private List<Fragment> fragment_list;
    private tab_finance_Fragment tab_finance_fragment;
    private tab_news_Fragment tab_news_fragment;
    private tabs_enti_Fragment tabs_enti_fragment;
    private tab_sport_Fragment tab_sport_fragment;
    private String[] title={"xxx"};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_, container, false);
        //Inflate the layout for this fragment

        //Subclass fragment is added to the linked list
        tabs_enti_fragment = new tabs_enti_Fragment();
        tab_finance_fragment = new tab_finance_Fragment();
        tab_news_fragment = new tab_news_Fragment();
        tab_sport_fragment = new tab_sport_Fragment();
        fragment_list = new ArrayList<>();
        tabLayout = view.findViewById(R.id.tablayout);
        viewPager2 = view.findViewById(R.id.viewPager2);

        fragment_list.add(tab_news_fragment);
        fragment_list.add(tabs_enti_fragment);
        fragment_list.add(tab_finance_fragment);
        fragment_list.add(tab_sport_fragment);



        viewPager2.setAdapter(new FragmentPagerAdapter(getChildFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragment_list.get(position);
            }

            @Override
            public int getCount() {
                return 4;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return title[position];
            }

        });

        tabLayout.setupWithViewPager(viewPager2,true);



        return view;
    }
    /*

    public Fragment newinstance(FragmentPagerAdapter fmadapter){
        View view = View.inflate(R.layout.fragment_news_, this, false);
        News_Fragment news_Fragment = new News_Fragment();
        viewPager2 = findViewById(R.id.viewPager2);

        return news_Fragment;
    }

*/
    



}

MainActivity.java source code:

kage com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.fragment.app.ListFragment;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class MainActivity extends AppCompatActivity {
    private Home_Fragment homeFragment;
    private News_Fragment newsFragment;
    private Profile_Fragment profileFragment;
    BottomNavigationView btnnavigationview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Bottom navigation bar
        homeFragment = new Home_Fragment();
        newsFragment = new News_Fragment();
        profileFragment = new Profile_Fragment();

        //Click the bottom navigation bar to switch page binding fragments
        settingdefaultfragment();



        //Click the bottom navigation bar to switch page binding fragments
        btnnavigationview = findViewById(R.id.btnnavigationview1);
        btnnavigationview.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                if(item.getItemId() == R.id.news){
                    fragmentTransaction.replace(R.id.framelayout,newsFragment);
                    // startActivity(new Intent(,NEW_fra.class));
                } else if (item.getItemId() == R.id.home) {
                    fragmentTransaction.replace(R.id.framelayout,homeFragment);
                } else if (item.getItemId() == R.id.profile) {
                    fragmentTransaction.replace(R.id.framelayout,profileFragment);
                }
                fragmentTransaction.commit();
                return true;
            }
        });















    }

    //Set the default locked main page
    public void settingdefaultfragment(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.framelayout,homeFragment);
        transaction.commit();
    }
}