Cannot resolve maketext() method of Toast

后端 未结 18 1139
南笙
南笙 2021-02-07 02:02

I am getting error while creating a Toast

Toast toast = Toast.makeText(this, text, duration);

I am getting cannot resolve ma

相关标签:
18条回答
  • 2021-02-07 02:36

    The makeText's signature is the following

    public static Toast makeText (Context context, CharSequence text, int duration)
    

    the first paramter has to be a context object. You put this, but this refers to this object and it can be something different from an Activity (a Fragment for instance).

    0 讨论(0)
  • 2021-02-07 02:37

    this in your case might not be the object of the activity. You might be using the Toast.makeText method inside you Click Listener object. To resolve this you need to use getApplicationContext() :

    Toast.makeText(getApplicationContext() , "Your Message", Toast.LENGTH_LONG);

    0 讨论(0)
  • 2021-02-07 02:38

    Instead of

    Toast toast = Toast.makeText(this, text, duration);  
    

    Add your activity name before "this" word

    Toast toast = Toast.makeText(MyActivity.this, text, duration); 
    
    0 讨论(0)
  • 2021-02-07 02:38

    In case of a Toast in a fragment inside a Tabbed Activity, use getContext() e.g.

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

    0 讨论(0)
  • 2021-02-07 02:41

    This might be helpful if you are trying to use Toast in Fragment:

    Toast.makeText(Your_Fragment_Name.super.getContext(), "Added", Toast.LENGTH_SHORT).show();
    
    0 讨论(0)
  • 2021-02-07 02:42

    Grab the context from the calling activity (eg. this or MainActivity.this) and pass it into the method your Toast resides in. That way it lives together with the calling activity.

    Application context, which you get from getApplicationContext() and getContext() is mainly for long running processes. Using it for short lived processes can lead to memory leaks.

    0 讨论(0)
提交回复
热议问题