Cannot include view in <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 get an error: "cannot use android.view.View for somepackage.Fragments.ToolbarFragment"

why does the android see the fragment as a general type of representation, and not as the class of the fragment that I specified?

+6
source share
2 answers

You call findViewById() . This is for searching a View , for example a widget.

If you want to find the fragment, call findFragmentById() on your FragmentManager , which you will get by calling getFragmentManager() (your own fragments) or getSupportFragmentManager() (backport fragment from support-v4 or support-v13 ) on your activity.

+12
source

Try this way

 somepackage.Fragments.ToolbarFragment toolbarFragment = (somepackage.Fragments.ToolbarFragment) findFragmentById(R.id.toolbar_fragment); 
+3
source

Source: https://habr.com/ru/post/978992/


All Articles