-
-
Save miroslavign/20fc00b35b967ee0ab573fb89b60e5a2 to your computer and use it in GitHub Desktop.
Kotlin Fragment to Activity Communication Example
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 ExampleFragment : Fragment() { | |
// this is the instance of our parent activity's interface that we define here | |
private var mListener: OnFragmentInteractionListener? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
} | |
fun onButtonPressed(uri: Uri) { | |
if (mListener != null) { | |
mListener!!.onFragmentInteraction(uri) | |
} | |
} | |
override fun onAttach(context: Context?) { | |
super.onAttach(context) | |
if (context is OnFragmentInteractionListener) { | |
mListener = context | |
} else { | |
throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") | |
} | |
} | |
override fun onDetach() { | |
super.onDetach() | |
mListener = null | |
} | |
/** | |
* Here we define the methods that we can fire off | |
* in our parent Activity once something has changed | |
* within the fragment. | |
*/ | |
interface OnFragmentInteractionListener { | |
fun onFragmentInteraction(uri: Uri) | |
} | |
} | |
class AddVehicleActivity : AddVehicleStep1.OnFragmentInteractionListener, AppCompatActivity() { | |
// this is the callback-like function that will run when the fragment | |
// tells it to | |
override fun onFragmentInteraction(uri: Uri) { | |
// save some data from the fragment... | |
// other business logic... | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment