Access button in MainActivity from fragment

45 Views Asked by At

I have 5 destinations in my app in order to make easy for the user to navigate between them, I have had used bottom navigation and fragment. All may destinations have a common floating action button, which will perform other task from one to other, in order to access it from a specific fragment I declared the button as public in the MainActivity, and access it in the fragments like this: (requireActivity() as MainActivity).fab. this is work with no problem, here is the problem I faced, when I set the fragment as home fragment and try to access the button the same why I do with other fragment I have this error

FATAL EXCEPTION: main
                 Process: com.example.invoicegenerator, PID: 6249
                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.invoicegenerator/com.example.invoicegenerator.MainActivity}: android.view.InflateException: Binary XML file line #12 in com.example.invoicegenerator:layout/activity_main: Binary XML file line #19 in com.example.invoicegenerator:layout/content_main: Error inflating class fragment

here is the method I create to access button

// Access the button in the MainActivity.
private fun accessMainButton(): FloatingActionButton {
    return (requireActivity() as MainActivity).fab
}

It worked for all fragment except the home fragment, I had tried most solutions here on stack over flow nothing worked.

I'm using Kotlin to program the android app.

0

There are 0 best solutions below