[android] Use Toast inside Fragment

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.

This question is related to android android-fragments android-activity toast

The answer is


You can get the current activity with getActivity()

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

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();

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


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();
    


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()

Using Kotlin

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

        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();
        }

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();
    }
}

}


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.


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();
}
}

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.


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();
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to toast

How to create Toast in Flutter? java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(); Custom toast on Android: a simple example Use Toast inside Fragment Call to getLayoutInflater() in places not in activity How to display Toast in Android? How to change position of Toast in Android?