"Adding Callbacks From Fragment To Activity Or Activity To Application In Android" @ http://blog.jakelee.co.uk/2018/10/22/adding-callbacks-from-fragment-to-activity-or-activity-to-application-in-android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface ActionHandler { | |
| fun handleAction(actionCode: String) | |
| } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| companion object { | |
| const val FRAGMENT_A_CLOSED = "com.example.fragment_a_closed" | |
| } | |
| fun closeFragment() { | |
| try { | |
| (activity as ActionHandler).handleAction(FRAGMENT_A_CLOSED) | |
| } catch (e: ClassCastException) { | |
| Timber.e("Calling activity can't get callback!") | |
| } | |
| dismiss() | |
| } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class MainActivity: ActionHandler { | |
| override fun handleAction(actionCode: String) { | |
| when { | |
| actionCode == FragmentA.FRAGMENT_A_CLOSED -> { | |
| doSomething() | |
| } | |
| actionCode == FragmentB.FRAGMENT_B_CLOSED -> { | |
| doSomethingElse() | |
| } | |
| actionCode == FragmentC.FRAGMENT_C_CLOSED -> { | |
| doAnotherThing() | |
| } | |
| } | |
| } | |
| // Usual activity setup code snipped | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment