Android imitates lazyfragment lazy loading of microblog – (2)

Time:2021-12-8

I left two questions last time
1. What happens when you jump back to another page?
2. What if there is another viewpager + fragment in the sub fragment?

Question 1

It doesn’t matter. It’s just that you won’t distribute the event of loading data when you come back. Tut
So I add a piece of code that uses a variable to judge. You don’t need to write it, but I think you jump to another page and the data fragment data should change, so distribute it

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

Question 2

Other logs are removed here to make it look clearer
I added a viewpager to towfragment, which contains towfragment 1 and 2
After entering the app, you can see that the father hasn’t shown it yet. Did the son load the data first?

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

In addition, the two sons in the bottom tab and towfragment were indifferent after the switch. They only loaded when the app was just opened. They didn’t even call the method to stop loading. There were no events distributed to their sons at all

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

So we have to make some more judgments according to the state of our father and son
First, solve the first problem. Before the parent fragment is displayed, the child fragment loads data. The problem is very simple. We only need to distribute the events that load data,Judge whether there is a parent fragment and whether it is visible.That’s it

According to this method in the fragment source code, the above problem can be solved

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

For example, when the parent fragment is not visible, you can exit the method directly, and distribution is not allowed

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

However, there is another problem, that is, no matter how to switch, the sub fragment will not distribute the event of loading or stopping loading data. Why is this??

From the beginning, we can see that when entering the homefragment, the sub fragments will also be separatedCall the setuservisiblehint method twice, set your visible state to true before entering. The following distribution event is invalid.

So I decided to call the distribution event again when entering its parent fragment to really load the data of the child fragment, such as

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

It can be seen that the switching is normal

Android imitates lazyfragment lazy loading of microblog - (2)

image.png

Finally here

The idea of lazy loading is over ~ next, add smartrefresh control to imitate the loading mode of microblog (of course, it can only be rudimentary)