【问题标题】:Limited access in 2nd fragment of FragmentPagerAdapterFragmentPagerAdapter 的第二个片段中的访问受限
【发布时间】:2018-07-09 19:44:26
【问题描述】:

我有两个类似onViewCreated的结构片段

//1st
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    textDebug1 = getActivity().findViewById(R.id.view_debug1); //from layout1
    textDebug2 = getActivity().findViewById(R.id.view_debug2); //from layout2
//2nd
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    textDebug1 = getActivity().findViewById(R.id.view_debug1); //<--gives  error; layout1
    textDebug2 = getActivity().findViewById(R.id.view_debug2); //from layout2

在 onCreateView 中我有相同的行但不同的布局。

     View rootView = inflater.inflate(R.layout.activity_frag_main, container, false);

TextViews 位于不同的布局中,如果我选择加载第一个片段,那么代码运行良好,但如果我选择第二个运行第一个片段,那么getActivity() 返回null。如果两者的创建相同,可能会导致这种情况?

【问题讨论】:

    标签: java android android-fragments fragment


    【解决方案1】:

    如果您查看 Fragment 生命周期,您会发现有一个 onAttach() 和一个 onDetach() 方法。它们指的是 Fragment 的状态。由于您使用的是 ViewPager,因此您的片段可能会被分离,getActivity() 可能会返回 null

    on this article 所述,ViewPager 中的 Fragment 会发生这种情况:

    当页面不再可见或与可见页面相邻时 ViewPager 要求适配器销毁它。然而 FragmentPagerAdapter 不会完全破坏片段。它调用 FragmentTransaction.detach(fragment),销毁fragment的 整个视图层次结构,但不是对象。下次 ViewPager 希望该页面可以检索到相同的片段对象和视图 被重建。在此过程中再次调用 onCreateView(),这是 初始化视图的逻辑所属的位置。

    正如on the docs所说:

    注意:如果您需要在 Fragment 中包含 Context 对象,您可以调用 getContext()。但是,请注意仅当片段附加到活动时才调用 getContext()。 如果片段尚未附加,或者在其生命周期结束时被分离,getContext() 返回 null

    您可以尝试的一件事是保留片段实例。在 Fragment 的 onCreate() 中,尝试调用方法 setRetainInstance(true);

    另外,请在此处查看this answerthis other one,它可能对您的用例有用。

    【讨论】:

      【解决方案2】:

      @Mauker 通过onAttach() 建议的另一个解决方案

      getActivity() returns null on fragment?

      但不是 adding mcontext=getContext(); 到每个 Fragment 开始添加这个到自己的 FragmentPagerAdapter 类扩展

      public class TabAdapter extends FragmentPagerAdapter {
      
      final int PAGE_COUNT = 2;
      private Context mContext;
      
      public TabAdapter(Context context, FragmentManager fm) {
          super(fm);
          mContext = context;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        相关资源
        最近更新 更多