我有一个带有一些片段的viewpager。 pageradapter在FormActivity中实例化为;
//initialise pager for swipe screens
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
然而,我需要访问MyPagerAdapter.getRegisteredFragment(),但我不知道适配器的对象名称是什么,或者如何从中检测它,getSupportManager(),不知何故? 这是viewpager代码;
public class MyPagerAdapter extends FragmentStatePagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("@string/form_instruct");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return FourthFragment.newInstance("FourthFragment, Instance 1");
//case 4: return FifthFragment.newInstance("ThirdFragment, Instance 3");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
@Override
public int getCount() {
return 4;
}
@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);
}
}
我调用adapter.getRegisteredFragment()
的方法public void DrawText() {
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
if (user.size() != 0) {
// Displaying the user details on the screen
Fragment n = adapter.getRegisteredFragment(0);
n.surnameText.setText(surname);
}else{
Log.e(TAG, "table not filled");
}
}
非常感谢帮助,谢谢。
答案 0 :(得分:1)
为此视图寻呼机创建一个对象
public MyPagerAdapter adapter;
然后实例化对象
adapter = new MyPagerAdapter(getSupportFragmentManager())
pager.setAdapter(adapter);
然后调用方法执行此操作
Fragment fragment = adapter.getRegisteredFragment(pager.getCurrentItem);