Android: ListView elements in ListFragment overlap themselves

I am solving a strange problem with ListFragments. I have a simple FragmentActivity function with one FrameLayout, which is a container for my ListFragment. I use my custom adapter for data. Everything worked fine until I turned the device around to change the orientation. After that, the list is viewed twice - one list overlaps the second. When I look at the list, only one of the lists moves, and it creates artifacts, as shown in the figure.

screenshot from emulator

I initialize the adapter in onCreateActivity, and I do nothing in the onDestroy method. Is there anything I have to do in the onDestroy method to clear the list. Please, have you ever encountered this problem? I really don’t know what to do with it.

Thanks!

+4
source share
1 answer

Sorry I didn’t add the code, but I really didn’t know which part could do this. But I finally realized the reason.

In the onCreate method of parent activity, I created a fragment by calling

if(mFragment == null) { mFragment = onCreatePane(); getSupportFragmentManager() .beginTransaction() .add(R.id.root_container,mFragment) .commit(); } 

I thought the test for null sufficient. but the contents of the fragment remain in FrameLayout either after onDestroy is called in Activity (by turning the device). This is strange, isn't it?

I tried putting this code in onStop()

 if(mFragment != null) { getSupportFragmentManager() .beginTransaction() .remove(mFragment) .commit(); } 

but the result was the same. The only solution I found was to replace the add() method with the replace() method. But does anyone know why removing the fragment did not help? And why does the fragment content remain in FrameLayout after the Activity is destroyed?

Thanks again.

EDIT:

Now I know what the problem is. I have to check savedStateInstance == null instead of mFragment == null . If I do not, the main action will restore the old fragment from the saved state, and it will also create a new fragment in my onCreate method.

+6
source

Source: https://habr.com/ru/post/1379226/


All Articles