I am trying to use a Fragment in a FragmentActivity like so:
TutViewerFragment viewer = (TutViewerFragment)
getSupportFragmentManager().findFragmentById(R.id.tutview_fragment);
And my TutViewerFragment
extends Fragment
. However I am getting an error:
Cannot cast from Fragment to TutViewerFragment.
I really don't understand why this is happening. Why can't it be cast?
You are extending the wrong Fragment class. Import android.support.v4.app.Fragment
instead of android.app.Fragment
.
As devconsole pointed out in the comment above: The class that extends Fragment needs to import
android.support.v4.app.Fragment;
and not
android.app.Fragment;
I guess it has to do with the Android Compatibility Package. Problem is now resolved!
Just in case people are looking for kotlin equivalent:
myFragmentClass = supportFragmentManager.findFragmentById(R.id.my_fragment) as MyFindOfFragment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With