Android: How to switch between multiple Fragments

Reprint please indicate the from silly child b_ mobile development (www.jianshu.com/users/d388b… Like can pay attention to me, not regular summary of the article! Your support is my motivation ha!

I. Application scenarios

Viewpager +Fragment to switch pages. In everyday application front pages, AD rotations, welcome pages, image switches, etc., it’s very, very widespread (really very widespread). GetActivity () may be null when switching between multiple fragments. For those who need it, check out “Android years, Handling getActivity() null days”.

For multi-page switching, the more common program is written, for example:

(1) Initialize Fragment

       Tab1Fragment tab1Fragment = new Tab1Fragment();
       Tab2Fragment tab2Fragment = new Tab2Fragment();
       Tab3Fragment tab3Fragment = new Tab3Fragment();Copy the code

(2) After storing the Fragment in the List, initialize the ViewPager adapter

fragmentList.add(tab1Fragment); fragmentList.add(tab2Fragment); fragmentList.add(tab3Fragment); viewAdapter = new MainPagerAdapter(getSupportFragmentManager(),fragmentList,titleList); viewPager.setAdapter(viewAdapter); viewPager.setCurrentItem(0); // The first one is selected by defaultCopy the code

(3) By implementing the setOnPageChangeListener interface, switch listener is realized

   viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });Copy the code

Second, apply ing-> code explanation

(1) Define a store Fragment entity class

/** * ViewPageInformation */ public static class ViewPageInfo { public String tag; public View view; public Fragment fragment; public ViewPageInfo(String tag, Fragment fragment){ this.tag = tag; this.fragment = fragment; }}Copy the code

The Fragment tag is used as a Fragment identifier, which can be used as a title. View refers to the Fragment bound view. Fragment is a fragment.

(2) Define a base class BaseTabFragment, suitable for multi-fragment switching scenarios.

/** * Created by wsy on 2016/8/15. */ public abstract class BaseTabFragment extends BaseFragment{ private ViewPager viewPager; private List fragList; protected FragmentStatePagerAdapter mAdapter; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewPager = (ViewPager) view.findViewById(R.id.viewpager); if (mAdapter == null){ fragList = new ArrayList<>(); addSubViewTab(); mAdapter = new FragmentStatePagerAdapter(getFragmentManager()) { @Override public Fragment getItem(int position) { return fragList.get(position).fragment; } @Override public int getCount() { return fragList.size(); } @Override public CharSequence getPageTitle(int position) { return fragList.get(position).tag; }}; if (viewPager ! =null) { viewPager.setAdapter(mAdapter); loadFinishView(viewPager, mAdapter); } }else{ if (viewPager ! =null) { viewPager.setAdapter(mAdapter); loadFinishView(viewPager, mAdapter); } } } public FragmentStatePagerAdapter getmAdapter() { return mAdapter; } public abstract void addSubViewTab(); public abstract void loadFinishView(ViewPager viewPager,FragmentStatePagerAdapter mAdapter); public void addTab(String tag, Class fragment){ fragList.add(new ViewPageInfo(tag, Fragment.instantiate(getActivity(), fragment.getName()))); } /** * ViewPageInformation */ public static class ViewPageInfo { public String tag; public View view; public Fragment fragment; public ViewPageInfo(String tag, Fragment fragment){ this.tag = tag; this.fragment = fragment; }}}Copy the code

AddSubViewTab and loadFinishView are abstracted by subclasses. AddSubViewTab is used by subclasses to determine which Fragment view to initialize. LoadFinishView is what to do after the Fragment is loaded (ViewPager configuration, Fragment operations, etc.). Because this code is the author with tabLayout abstract out of a parent class. Of course, in everyday development, programmers can replace a BaseFragment with their own base class Fragment.

(3) How to use it? The addSubViewTab abstract method is used to initialize the Fragment as follows:

MainTabFragment = new mainTabFragment () {@override public void addSubViewTab() {// Initialize the view to call addTab AddTab (" 1 "title, Tab1Fragment. Class); AddTab (" heading 2 ", Tab2Fragment. Class); AddTab (" title ", Tab3Fragment. Class); } @Override public void loadFinishView(ViewPager viewPager, FragmentStatePagerAdapter mAdapter) { mViewPager = viewPager; // The view is loaded and whatever you want to do is returned to you}}; getSupportFragmentManager().beginTransaction().add(R.id.test_contanter,mainTabFragment).commit();Copy the code

Three, the application of Ed -> achieve the effect

Here, the author has implemented a startup welcome interface, and joined the author’s personal online application Love Travel notes (welcome to use it, report the bug haha, will take one or two months to change the version, open source ~)

The running effect is as follows:




Welcome to.gif

Four,

I’ve been reading Retrofit2.0 lately and I want to write a few articles about Retrofit2.0 later. Not summarizing notes for a few days T T. Today about simple encapsulation multi Fragment switch, I hope you can help readers ~ mutual encouragement! Have what problem opinion also although carry ha!

Source code address:

Android teaches you how to easily encapsulate multi-fragment switching

I write to you as you struggle on your way of growing up

-d, thank you for reading.