与片段生命周期的onCreate问题被称为非存在的片段 [英] Problems with Fragment lifecycle and onCreate being called on non existent fragment

查看:255
本文介绍了与片段生命周期的onCreate问题被称为非存在的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试Android中的片段和我在与片段生命周期的一些容易混淆的行为。我有一个使用的布局在XML中的风景和肖像模式的一个活动。我有一些code,它访问了在片段布局之一定义的EditText对象。如果我开始在横向模式下工作的事情的应用程序。我访问该组件在onResume()方法的片段来更新一些文本。

I am testing fragments in Android and I'm having some confusing behavior with Fragment life cycle. I have a activity that uses layouts in xml for both landscape and portrait modes. I have some code that accesses a EditText object that is defined in one of the fragment layouts. If I start the app in landscape mode things work. I access the component in the onResume() fragment method to update some text.

根据文档的onResume()片段方法被调用时,片段是对用户可见。但是,如果我旋转屏幕,此方法被再次调用,即使这片段是不是在纵向布局定义。该呼叫的onCreate导致NullPointerException异常监守这个方法引用的EditText对象。为什么叫上不是新布局的一部分片段onResume方法?如何以及在哪里是修改片段布局数据的适当位置。我曾尝试在onStart,onResume,onActivityCreated等,但似乎都返回相同的错误。

According to the documentation the onResume() fragment method is called when the fragment is visible to the user. However, if I rotate the screen this method gets called again even though this fragment is not defined in the portrait layout. This call to onCreate causes a NullPointerException becuase this method references the EditText object. Why is onResume method called on a fragment that is not part of the new layout? How and where is the proper place to modify layout data in a fragment. I have tried onStart, onResume, onActivityCreated etc, but all seem to return the same error.

任何帮助将是最AP preciated。

Any help would be most appreciated.

推荐答案

当你旋转屏幕,Android的节省您的片段以捆绑并重新创建这些当它重新创建活动。这就是为什么你得到一个不存在的(实际上只是不可见)片段的呼叫。你需要处理的片段code这种情况下,或者仅仅是在土地和港口布局,在那里你片段可见性设置为 GONE 两个片段,如果你不'T需要它。

When you rotate the screen, Android saves your fragments in a Bundle and recreates them when it recreates the activity. That is why you get calls to a non-existing (actually just invisible) fragment. You need to handle this situation in the fragment code, or simply have both fragments in the land and port layouts, where you set the fragment visibility to GONE if you don't need it.

要检查的一个简单方法,如果该片段是在code可见的是这样的:

A simple way to check if the fragment is visible in code is this:

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
  }

如果容器为空,你的碎片正在从一个Bundle重新创建,将不会显示(因为没有容器)。然后,您必须检查是否 getView()为空和短路的$ C $据此℃。这会导致混乱了,所以要注意:)

If container is null, your fragment is being re-created from a Bundle and won't be shown (since there is no container). You then have to check whether getView() is null and short-circuit your code accordingly. This can get messy though, so beware :)

这篇关于与片段生命周期的onCreate问题被称为非存在的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆