【问题标题】:How to change view visibility at parent fragment from child fragment?如何从子片段更改父片段的视图可见性?
【发布时间】:2019-06-08 06:55:53
【问题描述】:

我正在使用具有层次结构的嵌套片段,如下所示: MainActivity>父片段>子片段。 mainactivity 包含很少的父片段,例如片段 10、片段 11、片段 12。 并且在父片段上也包含很少的片段,例如fragmentinti,fragmentdasar,fragmentindikator。 在 fragment10 我 hv relativelayout 阻塞列表视图,如果我没有 hv 数据,recyclerview 将显示信息。 在 fragmentinti 我 hv 过程中,如果在 fragment10 上的 hv 数据相关布局必须设置可见性 GONE,则从 API 获取。

我试图在 stackoverflow 上使用一些代码,但它仍然给我一个错误,

我测试的第一个代码

fragmentKelas10 = (fragmentKelas10) getParentFragment();
fragmentKelas10.getView().findViewById(R.id.nodata).setVisibility(View.GONE);

秒

fragmentKelas19 parentFrag = ((fragmentKelas10)fragmentKompetensiInti.this.getParentFragment());
parentFrag.setVisibilityNoData(View.GONE);

第三

(fragmentkelas10 getparentfragment()).setvisivity(View.GONE);

在我的 parentfragment 上添加公共方法

public void setVisibilityNoData(int visibility){
        nodata.setVisibility(visibility);
    }

*nodata 是相对布局

我尝试的所有上述代码都返回这样的错误消息

尝试在空对象引用上调用虚拟方法 'android.view.View edu.stikom.molearn.fragment.fragmentKelas10.getView()'

【问题讨论】:

  • 根据异常,您的片段为空。确保 getParentFragment() 没有返回 null。
  • 我也读过@zoe。即使那个可能的重复,仍然没有给我答案。我现在需要知道的是如何使用getparentfragment。

标签: java android xml android-fragments


【解决方案1】:

使您想要返回的活动或片段实现 OnFragmentInteractoinLister,当没有数据被调用时,它可以返回该片段或活动,您可以隐藏任何您想要的内容。

private OnFragmentInteractionListener mListener;
      public void onNoData() {
            if (mListener != null) {
                mListener.onFragmentInteraction();
            }
        }
    @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof OnFragmentInteractionListener) {
                mListener = (OnFragmentInteractionListener) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }

        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null;
        }

        public interface OnFragmentInteractionListener {

            void onFragmentInteraction();
        }

【讨论】:

  • 这不是我需要的真正答案,但这个答案给了我灵感,无论如何谢谢。
猜你喜欢
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多