Reputation: 26821
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?
Upvotes: 36
Views: 32537
Reputation: 4050
If you get this and are importing android.support.v4.app.Fragment
check that you use supportFragmentManager and Not fragmentManager.
Kotlin:
//DO
import android.support.v4.app.Fragment
myFragment = supportFragmentManager.findFragmentById(R.id.my_fragment) as MyFragment
//DON'T
import android.app.Fragment
myFragment = fragmentManager.findFragmentById(R.id.my_fragment) as MyFragment
Java:
//DO
import android.support.v4.app.Fragment
myFragment =(MyFragment) getSupportFragmentManager().findFragmentById(R.id.my_fragment)
//DON'T
import android.app.Fragment
myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.my_fragment)
Upvotes: 2
Reputation: 1110
Just in case people are looking for kotlin equivalent:
myFragmentClass = supportFragmentManager.findFragmentById(R.id.my_fragment) as MyFindOfFragment
Upvotes: 5
Reputation: 1264
As devconsole/igor specified, we need to ensure the Fragment class used in both classes is same. i.e. andorid.app.Fragment in both
public class WorkoutDetailFragment extends Fragment
and in the Activity class where we try to get reference of the fragment.
WorkoutDetailFragment workoutDetailFragment = (WorkoutDetailFragment)getFragmentManager().findFragmentById(R.id.detail_frag);
Ensuring the same Fragment class in both files will resolve class cast exception.
Hope this helps. I know its a bit late. I am new to Android and exploring the nuances of the wonderful language. Thanks to Stackoverflow for helping me with resolving these minor issues.
Upvotes: 3
Reputation: 26821
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!
Upvotes: 7
Reputation: 7915
You are extending the wrong Fragment class. Import android.support.v4.app.Fragment
instead of android.app.Fragment
.
Upvotes: 80