joshua-r2
11/27/2017 - 2:29 PM

Interface within a Fragment

This snippet illustrates how to use an Interface in the same file in which it is defined/instantiated. It isn't quite as straightforward as Java.

class NoteHome : FragmentEvent, AppCompatActivity() {



  override fun somethingHappened(){
    Toast.makeText(this, "It Happened", Toast.LENGTH_LONG).show()
  }


}
class ImplementingFragment : Fragment(){

  private lateinit var listener: FragmentEvent
  private lateinit var vFab: FloatingActionButton
  
  //Here is the key piece of code which triggers the interface
  override fun onAttach(context: Context?) {
          super.onAttach(context)
          if(context is FragmentEvent) {
              listener = context
          }
      }
      
    //Notice the onClickListener using our interface listener member variable
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val v: View? = inflater.inflate(R.layout.fragment_layout, container, false)
            vFab = v?.findViewById(R.id.fh_fab)
            vFab.setOnClickListener{listener.SomethingHappened()}
        return v
    }  
    
    
}



interface FragmentEvent{
    fun SomethingHappened()
}