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.


Solution 1:

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

Solution 2:

As stated by alfo888_ibg:

@Override
public void onClick(View arg0) {
   Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Just do:

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();

this worked for me.

Solution 3:

To help another people with my same problem, the complete answer to Use Toast inside Fragment is:

Activity activity = getActivity();

@Override
public void onClick(View arg0) {

    Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Solution 4:

When making a toast in fragment do as following:

Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();

When class is extending fragment it is necessary to use getActivity() since fragment is a subclass of activity.

Cheerse

Solution 5:

You can get the current activity with getActivity()

Toast.makeText(getActivity(),"Toast your message" ,Toast.LENGTH_SHORT).show();