Access parent activity views from fragment in tablayout?

Viewed 250

I am using TabLayout with ViewPager. I have 3 fragments and 3 tabs. I want to access the FloatingActionButton in activitymain.xml file.

In every fragment I write a code like this:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fab :View= (requireActivity() as MainActivity).findViewById(R.id.fab_main)

            fab.setOnClickListener {
                Toast.makeText(context,"Fragment1",Toast.LENGTH_SHORT).show()  
            }
        }

But when I click the FloatingActionButton in every fragment it gives me the same Toast message which is related to the last fragment. I want to perform different actions in every fragment when I clicked the button.

1 Answers

You could use FragmentStatePagerAdapter for tab function

class TabAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
..........
}

It will be make Fragment call onResume when the fragment is active. So you can like this in Fragment

override fun onResume() {
    super.onResume()

    val fab :View= (requireActivity() as MainActivity).findViewById(R.id.fab_main)

    fab.setOnClickListener {
        Toast.makeText(context,"Fragment1",Toast.LENGTH_SHORT).show()  
    }
}
Related