2017-08-24 105 views
0

我在1個活動中有4個片段。我需要確保在每個片段更改時都會刷新片段,因爲我在每個片段中都加載了JSON數據。我用FragmentPager適配器和RecyclerView到的數據顯示如何刷新FragmentPagerAdapter中的片段

這是我的適配器(SickAdapter.java)代碼:

public class SickAdapter extends FragmentPagerAdapter{ 

    private static final String TAG = SickAdapter.class.getSimpleName(); 

    private static final int FRAGMENT_COUNT = 4; 

    public SickAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     switch (position){ 
      case 0: 
       return new SickFragmentToAll(); 
      case 1: 
       return new SickFragmentToPending(); 
      case 2: 
       return new SickFragmentToApproved(); 
      case 3: 
       return new SickFragmentToDenied(); 
     } 
     return null; 
    } 

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

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position){ 
      case 0: 
       return "All"; 
      case 1: 
       return "Pending"; 
      case 2: 
       return "Approved"; 
      case 3: 
       return "Denied"; 
     } 
     return null; 
    } 
} 

在我的課(SickClass.java)創建SickClass和我通話SickAdapter,我爆炸他們,這是我的代碼:

public class SickClass extends Fragment { 

    private static final String TAG = SickClass.class.getSimpleName(); 

    private SickAdapter mAdapter; 
    private TabLayout tabLayout; 
    private ViewPager viewPager; 


    public SickClass() { 
    } 

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.employee_leave_class, container, false); 

     tabLayout = (TabLayout)view.findViewById(R.id.tabs); 
     viewPager = (ViewPager)view.findViewById(R.id.view_pager); 

     if(mAdapter == null) { 
      mAdapter = new SickAdapter(getChildFragmentManager()); 
     } 
     viewPager.setAdapter(new SickAdapter(getChildFragmentManager())); 
     tabLayout.setupWithViewPager(viewPager); 
     viewPager.setCurrentItem(1, true); 

     tabLayout.post(new Runnable() { 
      @Override 
      public void run() { 
       tabLayout.setupWithViewPager(viewPager); 
      } 
     }); 

     return view; 
    } 

} 
+0

使用'FragmentStatePagerAdapter' –

回答

0

嘗試下面的代碼重新加載你的片段;

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.detach(YOUR_FRAGMENT_NAME.this).attach(YOUR_FRAGMENT_NAME.this).commit(); 
+0

這裏我添加的代碼? –

+0

在片段類中,你想要重新加載 –

+0

你能舉個例子嗎? –