android Fragment issue with orientation change

安稳与你 提交于 2019-12-24 14:34:59

问题


I have activity and two layouts for it defined:

  1. layout-large-land
  2. layout

1st layout is for large screens in landscape mode, 2nd is for other cases. The 1st layout contains:

  1. fragment1
  2. fragment2

The 2nd layout contains:

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!