In my app there's 2 tabs (Android Design Support Library) this is the Fragment with 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;
}
I want my app refresh fragment on Swipe and on click the tabs title because this don't happen, I hope you can help me guys.
I am sure this is not the only/best way to do it. But this should solve the problem as it did to me.
Please write refresh() methods in both FragmentCanali and 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();
}
}}
It will be cleaner if you extend both the fragments from a base fragment which has abstract refresh() method.
In the onPageSelected() you can just call ((BaseFragment)adapter.getItem(position)).refresh()