Reputation: 3253
I'm trying to have a toast be displayed after I select a menu item from a navigation drawer and the app switches to that fragment
. I have this line of code inside the onCreate()
method for my fragment
so that it will be displayed when the fragment is inflated, except it's not working:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.post_layout, container, false);
//My toast wont work!!:(
Toast.makeText(Post_Fragment.this, "It worked!", Toast.LENGTH_SHORT).show();
return myView;
}
Any thoughts? Thanks for the help.
Upvotes: 0
Views: 1585
Reputation: 2509
Try changing:
Toast.makeText(Post_Fragment.this, "It worked!", Toast.LENGTH_SHORT).show();
to
Toast.makeText(getActivity(), "It worked!", Toast.LENGTH_SHORT).show();
or put the makeText()
call inside the onNavigationItemSelected()
method in the activity which houses the fragment. In which case your call would be similar to this.
Toast.makeText(this, "It workded!", Toast.LENGTH_SHORT).show();
The first parameter for makeText()
is a context object. From the docs a Context
is:
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Your activity class extends the context. Your fragment class does not. The method you're calling is static, so it does not have access to application-specific resources and classes/etc. Passing the context (your activity), gives it access to those resources.
Cheers
Upvotes: 1