Kotlin: Pass data from fragment to activity using interfaces

Viewed 25

I have a simple project that has a main activity, an interface and a fragment. I am trying to figure out, when a button is clicked in the fragment, how to pass a simple boolean to the main activity using the interface. Here is the interface:

    interface OnClickInterface {
fun onClick(proceed: Boolean)

}

Here is the fragment:

    class FragmentMain : Fragment() {

private lateinit var binding: FragmentMainBinding
var listener: OnClickInterface? = null

fun initOnClickInterface(listener: OnClickInterface){
    this.listener = listener
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = FragmentMainBinding.inflate(layoutInflater)
    binding.button.setOnClickListener { onClick(proceed)}
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
    return binding.root
}

private fun onClick(proceed: Boolean) {
    listener?.onClick(proceed) // Trigger the call back
}

companion object {
    var proceed : Boolean = true
    @JvmStatic
    fun newInstance() = FragmentMain().apply {  }
}

}

Here is the MainActvity:

    class MainActivity : AppCompatActivity(), OnClickInterface {

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    replaceFragment(FragmentMain())
    val obj = FragmentMain.newInstance()
    obj.initOnClickInterface(this)
}

override fun onClick(proceed: Boolean) {
    binding.mainTextView.text = proceed.toString()
}

}

Extension function to place fragment:

    fun AppCompatActivity.replaceFragment(fragment: Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.host,fragment)
transaction.addToBackStack(null)
transaction.commit()

}

The problem is that the call back from the fragment does nothing. It is simply ignored. Any help will be appreciated! Edit: Apparently in the line: listener?.onClick(proceed) the listener is always null!

0 Answers
Related