我一起使用嵌套片段和viewPager。以下是HomeFragment
的代碼,它是viewPager中的片段之一。 HomeFragment
包含另一個片段,稱爲FeedFragment
,它只是一個RecyclerView
。 FeedFragment
內部我正在使用回調接口,通知HomeFragment
已成功創建FeedFragment
。我遇到的問題是,第一次創建HomeFragment
,mListener
值設置爲HomeFragment
的一個實例,位於onCreateView
之內,並且所有內容都已正確加載。當我移動到viewPager不同的片段,並返回到HomeFragment
,HomeFragment
onCreateView
方法被調用,mListener
再次設置爲HomeFragment
實例和onCreateView
方法後,從FeedFragment
調用,但mListener
是null
這個時候。Android ViewPager嵌套片段生命週期
以下是FeedFragment代碼:繼
public class FeedFragment extends Fragment {
RecyclerView feedRecyclerView;
FeedRecyclerViewAdapter feedRecyclerViewAdapter;
private OnCompleteListener mListener;
public FeedFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_feed, container, false);
feedRecyclerView = (RecyclerView) view.findViewById(R.id.postFeedItemContainer);
feedRecyclerViewAdapter = new FeedRecyclerViewAdapter(getActivity());
feedRecyclerView.setAdapter(feedRecyclerViewAdapter);
feedRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mListener.onComplete(feedRecyclerViewAdapter, this);
return view;
}
public interface OnCompleteListener {
void onComplete(
FeedRecyclerViewAdapter feedRecyclerViewAdapter, FeedFragment feedFragment);
}
public void setmListener(OnCompleteListener mListener) {
this.mListener = mListener;
}
}
爲HomeFragment代碼:
public class HomeFragment extends Fragment implements FeedFragment.OnCompleteListener {
// presenter instance
private HomeFragmentPresenter homeFragmentPresenter = HomeFragmentPresenter.getInstance();
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
FeedFragment feedFragment = new FeedFragment();
feedFragment.setmListener(this);
fragmentTransaction.add(R.id.fragmentHomeFeedContainer, feedFragment);
fragmentTransaction.commit();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onComplete(FeedRecyclerViewAdapter feedRecyclerViewAdapter, FeedFragment feedFragment) {
homeFragmentPresenter.fetchDataForAdapter(feedRecyclerViewAdapter, feedFragment);
}
}