Android的碎片问题与方向改变 [英] android Fragment issue with orientation change
问题描述
我有活动,两个布局为它定义:
I have activity and two layouts for it defined:
- 布局大土地
- 布局
1的布局是在横向模式下大屏幕,第二是其他案件。
首届布局包含:
1st layout is for large screens in landscape mode, 2nd is for other cases. The 1st layout contains:
- 片段1
- fragment2
第二布局包含:
- 片段1
当我开始在横向模式下的应用大屏幕上时, getSupportFragmentManager()。findFragmentById()
叫 Activity.onCreate()
正确返回两个片段。方向改变为纵向后, getSupportFragmentManager()。findFragmentById()
为 fragment2
返回不为空,但它应该返回空
因为这个片段在此布局中定义。问题是返回的片段对象是不正确的,我得到空
指针异常而访问它。它应该是空
,不应该吗?
When I start the app in landscape mode on large screen, the getSupportFragmentManager().findFragmentById()
called in Activity.onCreate()
correctly returns both fragments. 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. The problem is that the returned fragment object is incorrect and I get null
pointer exceptions while accessing it. It should be null
, shouldn't it?
推荐答案
其实...我不认为它应该是空
。
Actually... I don't think it should be null
.
在你的布局大土地
布局显示在活动
的活动
将增加在 FragmentManager
的两个片段
。一旦你旋转你的活动
的 FragmentManager
保留它的状态,而片段
里面,它仍然有一个 Fragment2
在里面,这就是为什么 findFragmentById()
做不返回空
。
After your layout-large-land
layout is displayed in the Activity
, the Activity
will add those both Fragments
in the 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
.
的 Fragment2
将在那里,但它不会附着在活动
,您可以检查这种通过使用 fragment.isAdded()
或 fragment.isVisible()
。
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()
.
如果你的情况,你要知道,如果你的2窗格(横向)或1窗格(纵向),也许你应该做以下检查: findViewById(R.id.secondFragmentContainer) == NULL
。
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
.
这篇关于Android的碎片问题与方向改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!