Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast View to <fragment>

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?

like image 394
Jon Avatar asked Dec 02 '14 12:12

Jon


2 Answers

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.

like image 173
CommonsWare Avatar answered Oct 26 '22 12:10

CommonsWare


Try this way

somepackage.Fragments.ToolbarFragment  toolbarFragment = (somepackage.Fragments.ToolbarFragment) findFragmentById(R.id.toolbar_fragment);
like image 3
M D Avatar answered Oct 26 '22 14:10

M D