在我的应用程序中有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;
}
我希望我的应用程序刷新片段在Swipe上点击标签标题,因为这不会发生,我希望你能帮助我们。
答案 0 :(得分:6)
试试这个......
要刷新片段,您首先需要它的实例。
更改此
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
到
ArrayList<Fragment> fr_list = new ArrayList<Fragment>();
fr_list.add(new FragmentCanali());
fr_list.add(new FragmentPreferiti());
MyAdapter mMyAdapter = new MyAdapter(getChildFragmentManager(),fr_list);
viewPager.setAdapter(mMyAdapter);
在适配器中更改此
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 MyAdapter(FragmentManager fm,ArrayList<Fragment> fr_list) {
super(fm);
this.fr_list=fr_list;
}
@Override
public Fragment getItem(int position)
{
return fr_list.get(position);
}
public int getCount() {
return fr_list.size();
}
在片段内添加refresh()方法,并在需要时调用它
((FragmentCanali) mMyAdapter.fr_list.get(0)).refresh();
答案 1 :(得分:6)
我确信这不是唯一/最好的方法。但这应该解决问题,就像它对我做的那样。
请在两者中编写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()