为什么' onCreateView'旋转后调用片段的方法?

时间:2016-07-30 16:07:33

标签: android android-fragments android-lifecycle

我在主要活动中实现了一个列表片段。我用这段代码打开片段:

  fragmentTransactionChat = getSupportFragmentManager().beginTransaction();
    if(savedInstanceState == null) {
        itemFragment = ChatItemFragment.newInstance(1);
        fragmentTransactionChat.add(R.id.frame_main, itemFragment, "chatFragment").commit();
    }
    else {
        itemFragment = (ChatItemFragment) getSupportFragmentManager().findFragmentByTag("chatFragment");
    }

这是片段中的onCreateView方法:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    setRetainInstance(true);
    View view = inflater.inflate(R.layout.fragment_item_list, container, false);
    // Set the adapter
    final Context context = view.getContext();
    recyclerView = (RecyclerView) view.findViewById(R.id.list);
    if (mColumnCount <= 1) {
        linearLayoutManager = new PreCachingLayoutManager(context);
        recyclerView.setLayoutManager(linearLayoutManager);

    } else {
        recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
    }
    mAdapter = new PostRecyclerViewAdapter(getActivity(), mListener);
    recyclerView.setAdapter(mAdapter);
    RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
    if (animator instanceof SimpleItemAnimator) {
        ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
    }
    recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager, mAdapter) {
        @Override
        public void onBottomList() {
            floatingActionButton.hide();
        }
    });

    postProvider = PostProvider.getInstance(getActivity());
    postProvider.setCallListener(this);

    bindItems(view);

    if(savedInstanceState == null) {
        postProvider.loadPost();
    }
    bindNotificationManager();
    return view;
}

我的问题是当我旋转设备时,再次调用onCreateView方法并且mAdapter对象和其他对象为空,因此它会导致我的逻辑问题。 注意:旋转后我的主要活动不会添加我的片段,因为我已通过此条件命令处理它:

if(savedInstanceState == null)

问题是什么?!

1 个答案:

答案 0 :(得分:0)

问题出在getActivity()的{​​{1}}中。尝试使用null方法中的((Activity) getContext())来获得活动。