简体   繁体   中英

How to display a Toast using a Fragment within a Navigation Drawer

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM