Reputation: 29
I am trying to use a TabLayout with different fragments and have started with AndroidStudio's automatically generated code for the tabbed layout. I have not changed how the placeholder fragment is created, displayed, handled etc.: The fragment is handled by a FragmentPagerAdapter, which is used by a ViewPaper, which in turn is used to setup the TabLayout.
The layout already included a FAB. Its onClick looks like this:
fab.setOnClickListener { view ->
val currentFragment: Fragment = sectionsPagerAdapter.getItem(viewPager.currentItem)
when (viewPager.currentItem) {
0 -> doSomething()
1 -> (currentFragment as PlaceholderFragment).fabOnClick()
else -> doSomethingElse()
}
}
Eventhough the above code makes sure that fabOnClick()
is only called on the currently visible fragment, when I am trying to get a context using requireContext()
in the PlaceholderFragment, java throws the following exception:
java.lang.IllegalStateException: Fragment PlaceholderFragment{660c58b} (08f94c5f-64b3-4a50-a1d4-2f3a6c7b491c)} not attached to a context.
For some reason, the context is available in e.g. onResume()
in the PlaceholderFragment:
override fun onResume() {
super.onResume()
// Works fine
Toast.makeText(requireContext(), "placeholder", Toast.LENGTH_LONG).show()
}
fun fabOnClick() {
// Throws exception
Toast.makeText(requireContext(), "placeholder", Toast.LENGTH_SHORT).show()
}
I found this thread, Fragment not attached to a context, in which the solution was to commit a fragment transaction but all of this seems to be handled automatically in this case.
Upvotes: 0
Views: 1297
Reputation: 789
I just fixed an error somewhat similar to you in my code. With the same error you are getting. The idea is that I was initializing a string variable (NOT in MainActivity) with getResources(). However, the variable was not being initialized with context.getResources()
I was able to initialize this variable inside MainActivity and make it static so that I could just copy the value into the variable NOT inside MainActivity.
So, I think you should search for any variables that you are initializing with getResources and see if you are using a context or not.
Upvotes: 1