Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active September 15, 2022 14:01
Show Gist options
  • Save Audhil/bca34978bb60101dbeda910502ea7ed7 to your computer and use it in GitHub Desktop.
Save Audhil/bca34978bb60101dbeda910502ea7ed7 to your computer and use it in GitHub Desktop.
Android basic brush up - AtoF & FtoA communication
class DummyActivity : AppCompatActivity(R.layout.activity_dummy) {
private val btn by lazy {
findViewById<Button>(R.id.btn)
}
private val tv by lazy {
findViewById<TextView>(R.id.tv)
}
var aToFragCallback: ActivityToFragCallBack<String>? = null
override fun onResume() {
super.onResume()
var count = 0
btn.setOnClickListener {
aToFragCallback?.invoke("Hello from activity, count: ${++count}")
}
}
val fToActCallback: FragToActivityCallBack<String> = {
tv.text = it
}
}
class DummyFrag : Fragment(R.layout.frag_dummy) {
private lateinit var inflatedView: View
private val btn by lazy {
inflatedView.findViewById<Button>(R.id.btn)
}
private val tv by lazy {
inflatedView.findViewById<TextView>(R.id.tv)
}
private var fToActCallback: FragToActivityCallBack<String>? = null
override fun onAttach(context: Context) {
super.onAttach(context)
// f to a
fToActCallback = (context as? DummyActivity)?.fToActCallback
// a to f
(context as? DummyActivity)?.aToFragCallback = {
tv.text = it
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
inflatedView = view
var count = 0
btn.setOnClickListener {
fToActCallback?.invoke("Hello world from fragment, count: ${++count}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment