0

Almost in all articles I've read people use this approach for communicating between Fragments and an Activity:

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

But Why does people use this approach while we can pass an Interface or a function as constructor parameter of Fragment and then use it?

I mean we can do something like this inside Fragment(I've used Kotlin functions as constructor parameter but we can also use Interfaces):

class CategoryListFragment(private val onBtnAddCategoryClick: () -> Unit) : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val content = inflater.inflate(R.layout.fragment_category_list, container, false)
        return content
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fab_add_category.setOnClickListener {
            onBtnAddCategoryClick()
        }
    }

}

and use it like this inside Activity:

class MainActivity : AppCompatActivity() {

    companion object{
        const val TAG_ADD_CATEGORY_DIALOG = "TAG_ADD_CATEGORY_DIALOG"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.container, CategoryListFragment{
            Toast.makeText(this@MainActivity, "show add category", Toast.LENGTH_SHORT).show()
        })
        fragmentTransaction.commit()
    }

}

I think the second approach is better as we can do Dependency-Injection and also it's not required to do any upcasting etc.

Jack Jaki
  • 77
  • 5

1 Answers1

2

the problem is that during your application life cycle the system may need to destroy and recreate your fragment again but it will call the constructor with no parameters so your onBtnAddCategoryClick will not set. so you have to set that from your activity. This is also why you should pass the data between activities and fragments using bundle

Farid
  • 1,024
  • 9
  • 16