在我的应用程序中有2个选项卡(
Android设计支持库)这是带有ViewPagerAdapter的片段:
public class ListaCanali extends Fragment { public static TabLayout tabLayout; public static ViewPager viewPager; public static int int_items = 2 ; @Override public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) { View v =inflater.inflate(R.layout.lista_canali,container,false); //Titolo Fragment ((MainActivity) getActivity()).setActionBarTitle("Lista Canali"); //FindViewById tabLayout = (TabLayout) v.findViewById(R.id.tabs); viewPager = (ViewPager) v.findViewById(R.id.viewpager); //Funzioni Tab viewPager.setAdapter(new MyAdapter(getChildFragmentManager())); tabLayout.post(new Runnable() { @Override public void run() { tabLayout.setupWithViewPager(viewPager); } }); return v; } //Adattatore Tab class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0 : return new FragmentCanali(); case 1 : return new FragmentPreferiti(); } return null; } public int getCount() { return int_items; } public CharSequence getPageTitle(int position) { switch (position){ case 0 : return "Tutti"; case 1 : return "Preferiti"; } return null; }
解决方法
我相信这不是唯一/最好的方法.但这应该解决问题,就像它对我做的那样.
请在两者中写入refresh()方法
FragmentCanali和FragmentPreferiti Fragments.
public class ListCanali extends Fragment implements OnPageChangeListener{ private MyAdapter mAdapter; @Override public View OnCreateView (...) { ... if(mAdapter == null) { mAdapter = new MyAdapter(getChildFragmentManager()); } viewPager.setAdapter(mAdapter); viewPager.setOnPageChangeListener(this); ... } ... @Override public void OnPageSelected (int position) { switch (position){ case 0 : ((FragmentCanali)adapter.getItem(position)).refresh(); case 1 : ((FragmentPreferiti)adapter.getItem(position)).refresh(); } }}
如果从具有抽象refresh()方法的基本片段扩展两个片段,它将更加清晰.
在onPageSelected()中你可以调用((BaseFragment)adapter.getItem(position)).refresh()