I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment
). To this end, I save the activity in an attribute on the fragment when onAttach()
is called on the fragment. According to the docs, onAttach()
should be called before onCreateView()
, which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle()
from the Fragment
. However, that keeps throwing a NullPointerException
. What am I missing here?
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity.
Though you can add a Toolbar anywhere within your fragment's view hierarchy, you should generally keep it at the top of the screen. To use the Toolbar in your fragment, provide an ID and obtain a reference to it in your fragment, as you would with any other view.
A fragment represents a modular portion of the user interface within an activity. A fragment has its own lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is running.
You can access the Activity in a Fragment using getActivity()
. It can be called safely as soon as onActivityCreated()
was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.
If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated
was called.
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