Use Toast inside Fragment

AndroidAndroid FragmentsAndroid ActivityToast

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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 - Android

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 - Android

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 - Android

You can get the current activity with getActivity()

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

Solution 6 - Android

Making a Toast inside Fragment

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

OR

    Activity activityObj = this.getActivity();

    Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();

Solution 7 - Android

If you are using kotlin then the context will be already defined in the fragment. So just use that context. Try the following code to show a toast message.

Toast.makeText(context , "your_text", Toast.LENGTH_SHORT).show()

Solution 8 - Android

When calling Toast inside android fragment:

1. Activity mActivity=this.getActivity();  

2. Toast.makeText(mActivity,"Text you want to display",Toast.LENGTH_SHORT).show();

This works for me.

Solution 9 - Android

user2564789 said it right
But you can also use this in the place of getActivity()
which will make your toast look like this


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

Solution 10 - Android

A simple [Fragment] subclass.
Kotlin!
contextA - is a parent (main) Activity. Set it on create object.

class Start(contextA: Context) : Fragment() {

var contextB: Context = contextA;

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val fl = inflater.inflate(R.layout.fragment_start, container, false)

	// only thet variant is worked on me
    fl.button.setOnClickListener { view -> openPogodaUrl(view) }

    return fl;
}

fun openPogodaUrl(view: View) {        
    try {
        pogoda.webViewClient = object : WebViewClient() { // pogoda - is a WebView
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        }
        pogoda.loadUrl("http://exemple.com/app_vidgets/pogoda.html");
    }
    catch (e: Exception)
    {
        Toast.makeText(contextB, e.toString(), Toast.LENGTH_LONG).show();
    }
}

}

Solution 11 - Android

Using Kotlin

Toast.makeText(view!!.context , "your_text", Toast.LENGTH_SHORT).show()

Solution 12 - Android

In Kotlin android Toast.makeText(activity!!, "Your Text Here!", Toast.LENGTH_SHORT).show()

Solution 13 - Android

        public void onClick(View v) {
            Context context = v.getContext();
            CharSequence text = "Message";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

Solution 14 - Android

Unique Approach

(Will work for Dialog, Fragment, Even Util class etc...)

ApplicationContext.getInstance().toast("I am toast");

Add below code in Application class accordingly.

public class ApplicationContext extends Application {

private static ApplicationContext instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;
}

public static void toast(String message) {
    Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmammadaliusView Question on Stackoverflow
Solution 1 - AndroidCommonsWareView Answer on Stackoverflow
Solution 2 - AndroidSenimiiView Answer on Stackoverflow
Solution 3 - Androidalfo888_ibgView Answer on Stackoverflow
Solution 4 - AndroidSindri ÞórView Answer on Stackoverflow
Solution 5 - Androidandy bit1View Answer on Stackoverflow
Solution 6 - AndroidRameshView Answer on Stackoverflow
Solution 7 - AndroidCodemakerView Answer on Stackoverflow
Solution 8 - AndroidLakshan VithanaView Answer on Stackoverflow
Solution 9 - Androidvaibhav3027View Answer on Stackoverflow
Solution 10 - AndroidAlateyView Answer on Stackoverflow
Solution 11 - AndroidX-Black...View Answer on Stackoverflow
Solution 12 - AndroidRaheem JnrView Answer on Stackoverflow
Solution 13 - AndroidDonTiburonView Answer on Stackoverflow
Solution 14 - AndroidKhemraj SharmaView Answer on Stackoverflow