In my xml I have the following code:
<fragment android:name="somepackage.Fragments.ToolbarFragment"
android:id="@+id/toolbar_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and in my code I have:
private ToolbarFragment toolbarFragment;
toolbarFragment = (ToolbarFragment) findViewById(R.id.toolbar_fragment);
I receive the error: "cannot cast android.view.View to somepackage.Fragments.ToolbarFragment"
why is android seeing the fragment as a generic view type instead of as the fragment class that I specified?
You are calling findViewById(). That is for finding a View, such as a widget.
If you want to find a fragment, call findFragmentById() on your FragmentManager, which you get by calling getFragmentManager() (native fragments) or getSupportFragmentManager() (fragments backport from support-v4 or support-v13) on your activity.
Try this way
somepackage.Fragments.ToolbarFragment toolbarFragment = (somepackage.Fragments.ToolbarFragment) findFragmentById(R.id.toolbar_fragment);
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