Skip to content

Instantly share code, notes, and snippets.

@jquerius
Last active May 3, 2021 22:14
Show Gist options
  • Save jquerius/40aa61b2ff4d0b1ae267212d7dd965e5 to your computer and use it in GitHub Desktop.
Save jquerius/40aa61b2ff4d0b1ae267212d7dd965e5 to your computer and use it in GitHub Desktop.
Kotlin Fragment to Activity Communication Example
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)
}
}
@lamvann
Copy link

lamvann commented Dec 5, 2018

Here's a more idiomatic way of writing your onButtonPressed function :)
fun onButtonPressed(uri: Uri) = mListener?.let{ it.onFragmentInteraction(uri) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment