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. 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 .
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 .
上一篇: 片段在方向改变时恢复状态
下一篇: Android的碎片问题与方向的变化
