Problem with android fragments with orientation change

I have activity and two layouts for it:

  • layout-large-land
  • location

The first layout for large screens in landscape mode, the second for other cases. The first layout contains:

  • fragment1
  • FRAGMENT2

The second layout contains:

  • fragment1

When I launch the application in landscape mode on the big screen, getSupportFragmentManager().findFragmentById() , called in Activity.onCreate() , correctly returns both fragments. After changing the portrait orientation, getSupportFragmentManager().findFragmentById() does not return 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 when accessing it. It must be null , right?

+1
android android-orientation fragment
source share
1 answer

Actually ... I do not think it should be null .

After your layout-large-land appears in the Activity , the Activity will add these Fragments tags to the FragmentManager . When you rotate your Activity , the FragmentManager saves its state and Fragments inside it, and there is still Fragment2 , which is why findFragmentById() does not return null .

Fragment2 will be there, but it will not be tied to Activity , and you can check this using fragment.isAdded() or fragment.isVisible() .

If in your case you want to find out if your 2-panel (landscape) or 1-band (portrait) one, perhaps you should do the following check: findViewById(R.id.secondFragmentContainer)==null .

+3
source share

All Articles