片段实例化使用泛型类型,OnCreate方法不调用

时间:2015-08-21 13:42:46

标签: java android generics android-fragments android-adapter

我有一个以这种方式创建片段的适配器:

public class FooAdapter<T extends Fragment> extends FragmentPagerAdapter {
   private Class<T> c;
   public FooAdapter(FragmentManager fm,Class<T> c) {
      super(fm);
      this.c = c;
   }

   @Override
   public Fragment getItem(int position) {
      try {
         T fragment = c.newInstance();
         return fragment;
      } catch (InstantiationException e) {
         e.printStackTrace();
      } catch (IllegalAccessException e) {
         e.printStackTrace();
      }
      return null;
   }
}

适配器的实例化:

new FooAdapter<BarFragment>(getSupportFragmentManager(),BarFragment.class)

我将日志放入BarFragment的onCreate(和onAttach,onCreateView),但没有记录!

public class BarFragment extends Fragment{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "on create view");
    }
}

1 个答案:

答案 0 :(得分:0)

首先,你的onCreate方法是错误的,你应该使用onCreateView方法并忘记onCreate。

这样的事情:

public class BarFragment extends Fragment{

    public BarFragment(){

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(LAYOUT YOU WANT TO INFLATE, container, false);

        return rootView;
    }
}

我现在更深入地了解您的适配器代码。