0

My main fragment has too many views to load because the lines of code in the file are increasing. To avoid this I decide to separate views using a child fragment. So now upper views are in the child fragment and the remaining bottom views are in the main fragment. Till this ok.

Now I am opening a new fragment by clicking one view from the main fragment. When I came back to the main fragment it is reloading the child fragment because of that I am getting NullPointerException and the app crashed.

Following is the way I am adding child fragments.

 childFragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, fragment)
                            .commitAllowingStateLoss()

For more understanding.

enter image description here

I am using Navigation with BottomNavigationBar.

  1. How to avoid this?
  2. In some cases, fragment views are flickering when back to that fragment. How to avoid that?

1 Answers1

0

For your first question you want to avoid putting the fragment in the backstack.

 childFragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, fragment)
                            .addToBackStack(null)//<-- Here
                            .commitAllowingStateLoss()

For your second question Fragments are destroyed to conserve memory,typically happens when you can't see it. As such the recreation process could take some time, depending on how heavy the view is, thus the blinking.

The only way to stop it from blinking is to make sure the Fragment isn't doing so much that it can't seamlessly load back in.

You could do this by lazy loading your more heavy views, like lists, videos, and large images.

You could also look into Fragment transitions. These could visually smooth out the process of loading.

Here is a great source for some standard animations. Fragment transaction animation: slide in and slide out

avalerio
  • 2,072
  • 1
  • 12
  • 11
  • Thank you. The first question when I use add() is worked fine. I am new to Android so I am not getting what exactly I should do to avoid blink. Please explain in little detail. Any link or example. – Shyamaly Lakhadive Dec 13 '21 at 07:03
  • Its probably better that you post the blinking `Fragment`s code. Its an optimization problem, you're probably doing too much in `Fragment` for it to be done at the same time as the rest of the screen thus it blinks in. – avalerio Dec 13 '21 at 07:07