【问题标题】:fragment.getView() return null after backpressedfragment.getView() 回压后返回 null
【发布时间】:2013-12-10 03:29:00
【问题描述】:

我尝试在活动的附加fragment 下更改textview,因此我将attachedFragment 存储为变量,如下代码所示

    @Override
    public void onAttachFragment(android.support.v4.app.Fragment fragment) {
        super.onAttachFragment(fragment); 
        attachedFragment = fragment;
    }

然后当点击按钮时,我调用以下代码

        if(attachedFragment !=  null && attachedFragment.getView() != null)
        {
            TextView tvGender = (TextView) attachedFragment.getView().findViewById(R.id.tv_gender);
            if(tvGender!=null)
                tvGender.setText(R.string.title_step_one_gender);
        }

当我开始活动时,它工作正常,直到我变成下一个片段并按下; attachedFragment.getView() 总是返回 null

我的问题:

  1. 怎么可能在第一次没问题的情况下返回null?
  2. 更改 textview/任何其他控件的最佳解决方案是什么 在片段内?有很多碎片,我只需要 更改附加的片段。

nb:以上所有代码都在主要活动下

【问题讨论】:

  • 我认为除了检查 attachFragment != null 之外,您还应该确保 attachFragment.isDetached() 也为 false。

标签: android android-fragments


【解决方案1】:

如果我误解了您的问题,请纠正我。听起来您的情况是,您附加片段A,然后附加片段B,然后按回,留下片段A。在这种情况下,附加片段只是一个变量,因此它继续指向B,但是由于B现在是分离的,它是空的。按返回不会用片段 A 重新填充变量 attachFragment。

尝试使用 findFragmentById 或 findFragmentByTag。查看此thread 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多