[英]android Fragment issue with orientation change
I have activity and two layouts for it defined: 我有活动和两个布局定义:
1st layout is for large screens in landscape mode, 2nd is for other cases. 第一种布局适用于横向模式的大屏幕,第二种布局适用于其他情况。 The 1st layout contains:
第一个布局包含:
The 2nd layout contains: 第二个布局包含:
When I start the app in landscape mode on large screen, the getSupportFragmentManager().findFragmentById()
called in Activity.onCreate()
correctly returns both fragments. 当我在大屏幕上以横向模式启动应用程序时,在
Activity.onCreate()
调用的getSupportFragmentManager().findFragmentById()
Activity.onCreate()
正确返回两个片段。 After orientation change to portrait, getSupportFragmentManager().findFragmentById()
returns not null for fragment2
, but it should return null
because this fragment is not defined in this layout. 将方向更改为纵向后,
getSupportFragmentManager().findFragmentById()
对于fragment2
不返回null
,但它应返回null
因为此片段未在此布局中定义。 The problem is that the returned fragment object is incorrect and I get null
pointer exceptions while accessing it. 问题是返回的片段对象不正确,并且在访问它时会得到
null
指针异常。 It should be null
, shouldn't it? 应该是
null
,不应该吗?
Actually... I don't think it should be null
. 实际上......我不认为它应该是
null
。
After your layout-large-land
layout is displayed in the Activity
, the Activity
will add those both Fragments
in the FragmentManager
. 在
Activity
显示layout-large-land
布局后, Activity
将在Fragments
中添加这两个FragmentManager
。 Once you rotate your Activity
, the FragmentManager
retains it's state, and the Fragments
inside it, and it still has that Fragment2
in it, and that is why findFragmentById()
does not return null
. 一旦你旋转你的
Activity
, FragmentManager
保留它的状态,并且里面有Fragments
,它仍然有Fragment2
,这就是为什么findFragmentById()
不返回null
。
The Fragment2
will be there, but it won't be attached to the Activity
, and you can check this by using fragment.isAdded()
or fragment.isVisible()
. Fragment2
将存在,但它不会附加到Activity
,您可以使用fragment.isAdded()
或fragment.isVisible()
来检查它。
If in your case, you want to know if your 2-pane (landscape) or 1-pane(portrait), maybe you should do the following check : findViewById(R.id.secondFragmentContainer)==null
. 如果在您的情况下,您想知道您的2窗格(横向)或1窗格(纵向),可能您应该执行以下检查:
findViewById(R.id.secondFragmentContainer)==null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.