我创建了许多片段,Fragment1,Fragment2 ..,Fragment50在第一个带有监听器方法的片段中我想调用Fragment40。但我没有管理。在侦听器内部,这些行运行
pager.setCurrentItem(0);
pager.setCurrentItem(pager.getCurrentItem() + 1);
pager.setCurrentItem(pager.getCurrentItem() - 1);
But pager.setCurrentItem(40); not run. Gives errors. Any help please?
//First Fragment01
//I want to call Fragment40
public class Frag_2 extends Fragment implements
OnClickListener, AdapterView.OnItemSelectedListener {
//....................................................
public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);
final ViewPager pager = (ViewPager) getActivity().findViewById(R.id.pager);
View txtdersHakkinda1 = (View) getActivity().findViewById(R.id.txtDersHakkinda1);
txtdersHakkinda1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(pager.getCurrentItem()+40); // not run
// pager.setCurrentItem(0); //runs
// pager.setCurrentItem(pager.getCurrentItem() + 1);
// pager.setCurrentItem(pager.getCurrentItem() - 1);
}
} );
//......................................................................
}
/////////////////////// If many fragments --> FragmentStatePagerAdapter /////////////
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new Frag_1<Object>());
fragments.add(new Frag_2());
fragments.add(new Frag_3());
fragments.add(new Frag_4());
.....................
fragments.add(new Frag_50());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
答案 0 :(得分:0)
将此方法添加到适配器:
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
你不能得到这样的项目:adapater.getRegisteredFragment(viewPager.getCurrentItem())