问题
I have activity and two layouts for it defined:
- layout-large-land
- layout
1st layout is for large screens in landscape mode, 2nd is for other cases. The 1st layout contains:
- fragment1
- fragment2
The 2nd layout contains:
- fragment1
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?
回答1:
Actually... I don't think it should be null
.
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
.
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()
.
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
.
来源:https://stackoverflow.com/questions/15814061/android-fragment-issue-with-orientation-change