Android FragmentStatePagerAdapter预加载片段

时间:2016-05-09 15:38:55

标签: android android-viewpager

使用FragmentStatePagerAdapter在ViewPager上显示3个片段。

我将这些片段和3个片段命名为自定义布局

  

1.StepOneFragmet

     

2.StepTwoFragmet

     

3.StepThreeFragmet

我需要从Server获取数据并将这些数据分别绑定到不同的片段中。当我加载viewpager时,如何创建和初始化3个片段?

如果我访问StepThreeFragment,它将返回NullpointerException。这意味着系统尚未创建和初始化Fragment。

有我的代码:

的活动:

mPager = (ViewPager) findViewById(R.id.pager);
mFragments = new ArrayList<>();
mFragments.add(new StepOneFragment());
mFragments.add(new StepTwoFragment());
mFragments.add(new StepThreeFragment());

mPagerAdapter = new StepPagerAdapter(getSupportFragmentManager(),mFragments);
mPager.setAdapter(mPagerAdapter);

StepThreeFragment f = (StepThreeFragment)((StepPagerAdapter) mPager.getAdapter()).getmFragments().get(2);
f.textView_profile.setText("1111");//--->NullPointerException

StepPagerAdapter:Code

public ArrayList<Fragment> getmFragments(){
    return mFragments;
}

@Override
public int getCount() {
    return 3;
}

@Override
public Fragment getItem(int position) {
    return mFragments.get(position);
}

StepThreeFragment :(例如 - &gt; TextView的setText)

Code

2 个答案:

答案 0 :(得分:1)

的活动:

//assign MyObject some valu form your web services

mPagerAdapter = new StepPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.addFragments(MyObject obj);

StepOneFragment.java

    public static final StepOneFragment newInstance( MyObject obj ){

    StepOneFragment f = new StepOneFragment();

    // Get arguments passed in, if any
    Bundle args = f.getArguments();
    if (args == null) {
        args = new Bundle();
    }

    // Add parameters to the argument bundle
    args.putParcelable("obj", obj );          // clone or referenced?

    MyObject implements parcelable
    f.setArguments(args);

    return f;

    }

     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyObject object = getArguments().getParcelable("obj");

     }

Fragmentstatepageradapter:

public fraf extends FragmentStatePagerAdapter{

    List<Fragment> fragments = new ArrayList();

    public fraf(FragmentManager fragmentManager) {
         super(fragmentManager);
    }

    public void addFragments(Myobject obj){

        fragments.add(StepOneFragment.newInstance(obj));
        fragments.add(StepTwoFragment.newInstance(obj));
        fragments.add(StepThreeFragment.newInstance(obj));
        notifydatasetchanged();

     }

     @Override
     public int getCount() {
        return fragments.size();
     }

     @Override
     public Fragment getItem(int position) {
        return mFragments.get(position);
     }
}

答案 1 :(得分:0)

试试这个:

StepThreeFragment f = (StepThreeFragment)((StepPagerAdapter) mPager.getAdapter()).getItem(2);
f.textView_profile.setText("1111");