Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentActivity: Cannot cast from Fragment to derived class

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?

like image 672
IgorGanapolsky Avatar asked Mar 06 '12 15:03

IgorGanapolsky


3 Answers

You are extending the wrong Fragment class. Import android.support.v4.app.Fragment instead of android.app.Fragment.

like image 72
devconsole Avatar answered Oct 03 '22 21:10

devconsole


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!

like image 28
IgorGanapolsky Avatar answered Oct 03 '22 19:10

IgorGanapolsky


Just in case people are looking for kotlin equivalent:

myFragmentClass = supportFragmentManager.findFragmentById(R.id.my_fragment) as MyFindOfFragment
like image 26
MFAL Avatar answered Oct 03 '22 20:10

MFAL