当我使用getView()获取ViewPager中片段的根视图时,它返回null

时间:2017-06-08 13:59:42

标签: android android-fragments android-viewpager

我有一个具有两个片段的活动,这些片段由ViewPager呈现给用户。所以,我为ViewPager的适配器(MainFragsAdapter类)创建了一个扩展FragmentStatePagerAdapter的类,并且我覆盖了它的一些方法。 我想从主机Activity中获取我的ViewPager中的片段实例,并通过getView()方法获取当前片段的根视图。

我通过在Activity的onCreate()中键入以下内容来获取片段的实例但该实例的getView()返回null:

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mainFragsAdapter = new MainFragsAdapter(getSupportFragmentManager());
    viewPager = (ViewPager)findViewById(R.id.Pager);
    viewPager.setAdapter(mainFragsAdapter);

    int index = viewPager.getCurrentItem();
    if(index == 0) {

 Fragment1 fragment = (Fragment1)viewPager.getAdapter().instantiateItem(viewPager, index);
 View v = fragment.getView();
 Log.e("Frag1View",v.toString()); //At this point, I'm getting NullPointerException 
                                   //because getView() returns null.(Fragment isn't null)

     }else if(index == 1){

 Fragment2 fragment =(Fragment2)viewPager.getAdapter().instantiateItem(viewPager, index);

   }
}

My FragmentStatePagerAdapter:

public class MainFragsAdapter extends FragmentStatePagerAdapter {

     private SparseArray<Fragment> fragments = new SparseArray<>();
     private Fragment currentFragment;

     private int NUM_ITEMS = 2;

     public MainFragsAdapter(FragmentManager fm,Context context) {
    super(fm);           
      }

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

  @Override
  public Fragment getItem(int position) {

    if(position == 0){

            this.currentFragment = Fragment1.createInstance();

                }
        if(position == 1){

            this.currentFragment =Fragment2.createInstance();
          }

        return this.currentFragment;
      }

    @Override
     public Object instantiateItem(ViewGroup container, int position) {

     Fragment fragment = (Fragment)super.instantiateItem(container,position);
     fragments.put(position,fragment);
     return fragment; }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    fragments.remove(position);
    super.destroyItem(container,position,object); 
     }

    public Fragment getRegisteredFragment(int position) {

    return fragments.get(position);
  }
}

我该如何解决这个问题?谢谢你的帮助。

0 个答案:

没有答案