How to handle network calls inside a Fragment

前端 未结 7 1107
攒了一身酷
攒了一身酷 2021-01-31 23:21

I have the following situation:

I have an Activity that hosts a ViewPager, and I have 4 Fragments;

the ViewPager

7条回答
  •  轮回少年
    2021-01-31 23:43

    Let me introduce my idea to you:

    • getCurrentItem()
      Method of ViewPager
    • getItem(int position)
      Method of FragmentPagerAdapter Return the Fragment associated with a specified position.

    You can define an Interface holding the method for Network I/O like

    public Interface INetworkOnFragment{
     void handle(){
             //...
               }  
    }
    

    And implement it on your fragments and handle their own business logic (Network calls).

    In main Activity ,set ViewPager.OnPageChangeListener on ViewPager object like here:

        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
    public void onPageScrollStateChanged(int state){
    //donothing
    }
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){
    //donothing
    }
    public void onPageSelected(int position){
           INetworkOnFragment interface =(INetworkOnFragment) (pager.getAdapter().getItem(position));//get the current fragment and call handle method on it,dont need to care about whichever fragment it is . 
    interface.handle()
    }
    });
    

    The most important is onPageSelected(int position),Inside the callback it get the current fragment and call handle method on it,dont need to care about whichever fragment it is .

    Remember the handle method are called in Activity and not in fragments.All the Network calls are implemention of Interface,which make it easy to deal in Activity.

提交回复
热议问题