Use Toast inside Fragment

mammadalius picture mammadalius · May 26, 2012 · Viewed 159.6k times · Source

I'm trying to show a Toast Message when user click on a Button inside a Fragment. The problem is I cannot access the activity to show the Toast on it.

Here's the source of Fragment:

    public class FrgTimes extends Fragment
    {
        ScrollView sv;
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) 
        {
            if (container == null) { return null; }

            sv = (ScrollView)inflater.inflate(R.layout.frg_times, container, false);

            btnTime1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

            //******  HERE's the PROBLEM  ********
            Toast.makeText(<The Activity>, "Please long press the key", Toast.LENGTH_LONG );

            }});

            return sv;
        }

and Here's what I've been tried.

Toast.makeText( getActivity()  , ...
Toast.makeText( getView().getContext()  , ...
Toast.makeText( getActivity().getApplicationContext()  , ...
Toast.makeText( sv.getContext()  , ...
Toast.makeText( sv.getRootView().getContext()  , ...

In Debug I can see that all of these codes run without any exception but no TOAST being displayed.

Answer

CommonsWare picture CommonsWare · May 26, 2012

You are not calling show() on the Toast you are creating with makeText().