Why is there such a thing

A project launched earlier this year plans to use JetPack’s Navigation framework, so how to pass data between fragments becomes a new problem. There are no apis for fragments like setResult and onActivityResult, and Navigation has no support for them either. There is a new API in the latest frag-1.3.0-Alpha08, but forget it after you see a few alpha-characters. So I came up with a method that has the following advantages over a series of officially recommended methods:

  • Matches are performed using type signatures without passing String keys
  • Pass objects of any type directly, no implementation requiredSerializableorParcelableinterface
  • There is no need to declare interfaces or viewModels, LiveData, etc

1. Introduction method

1. Add the following code in the appropriate place in your Build. gradle file at the root of your Android project:

	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}
Copy the code

2. Add the following code in the appropriate place in your build.gradle file under your module:

Dependencies {implementation 'com. Gitee. Numeron: mortar: 0.1.0 from'}Copy the code

2. The initialization

1. In the onCreate method of the Activity with Navigation enabled, before setContentView, call the following methods:

mortarEnabled()
Copy the code

3. Usage

1. Use onResult method in AFragment to receive data:

onResult<List<User>> { resultCode: Int, list: List<User>? -> if(resultCode == RESULT_OK) { if(! list.isNullOrEmpty()) { //TODO() } } else { //TODO() } }Copy the code

2. Use the setResult method in the BFragment to pass data:

val userList: List<User> = ...
setResult(RESULT_OK, userList)
Copy the code

3. When the BFragment is returned to AFragment, the Lambda callback previously set through the onResult method will run.

  • Note:onResultandsetResultThe types of the passed arguments must be the same. MutableList and List are different. When either of the two names contains a MutableList, declare the List as a List.

4. Principle analysis

  • MortarThrough theFragmentManagerRegistered inFragmentLifecycleCallbacksTo listen in on allFragmentLife cycle, and in eachFragmenttheonViewCreatedMethod to find theFragmentWaiting for the result instance and processing the callback.
  • Whether it’ssetResultThe type passed by the method, oronResultMethod waits for one of the typesStringType, which is encapsulated in theTypedValueorTypedCallbackIn this case, this issetResultandonResultThe key to matching between. (Reference hereGson)

5. At the end

The above two points are the main ideas of the whole Mortar, which has been running stably in the company’s project. Welcome start: github.com/xiazunyang/…