1

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?

pb2q
  • 58,613
  • 19
  • 146
  • 147
cubesoft
  • 3,448
  • 7
  • 49
  • 91

1 Answers1

4

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.

Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
  • Let's say you have 1 button on fragment1 and activity is displaying with portrait layout. you want to open fragment2 being its clicked. after it's clicked fragment2 is opened everything is ok so far, my problem starts here, when I change the orientation from portrait to landscape fragment1 is no visible. How could I provide that fragment1 and fragment2 should stand together even though I change the orientation? – Mustafa Güven Jun 12 '14 at 07:21