1.3.0-alpha04 Fragment result api


On April 29, 2020, the  androidx. fragment:fragment : version 1.3.0-alpha 04, the modified version discards the previous fragment data transmission mode and adds a new API, as shown in the figure below


In the past, fragments should have been used to transfer data. There are many ways to obtain fragment instances, arguments, callbacks, and eventbus. In the past, most of the transfers needed to hold instances, which is very dangerous

However, Google has launched a new API. Now it is recommended to use the new API to transfer data. In version 1.3.0-alpha 04, the result API is added to operate

Very simple. If you want to transfer between two fragments, you need to use two APIs, one for sending and one for receiving. Here is a test. First, start a splash fragment and send a data to the home fragment at the end of the start page

Don’t forget to add references

implementation "androidx.fragment:fragment-ktx:1.3.0-rc02"

When sending

On receiving

This is not clear at a glance, these two methods can be used directly, kotlin’s own API, click in to see the source code

It is found that the method in parent fragment manager is simplified by kotlin

Now run a wave, start page ends, enter homefragment, and then we will receive the data we sent at the same time

The above is the delivery method of the same level of two fragments. If you change the scenario, when the fragment is a subset, the listening will be different. Here you create a new tabfragment, and then there are two sub tabs in the tabfragment. Now the sub tab has to transfer data to the tabfragment

First of all, it’s the same. Register in tabfragment to receive

Instead of using the parent fragment manager directly, you need to use the child fragment manager to register. Otherwise, it will be invalid, and then it will be sent the same. Here, a textview is displayed in the sub tab, and a data will be sent when you click textview

Then run a wave

In another scenario, if the data is transferred from the tabfragment to the subtab, the subtab will receive it. Here, add a hover button in the tabfragment and click the button to transfer the data to the subtab

At this time, sending is different, because it is sent to the child tab, so you need to use the child fragment manager to send

Run a wave to see

Here you need to pay attention to the registered key, do not repeat the registration, otherwise only one can receive data

This method does not hold the reference of the other party, which avoids many unknown problems. The listener with its own life cycle will be destroyed and removed at the same time