Using Toast
in the MainActivity
works fine
Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();
but when I use it in a class, getApplicationContext()
, gets red lined and it does not work. How can I make it work in a class?
You need to pass the context from Activity to the non Activity class and use the same there
new NonActivityClass(ActivityName.this);
Then
COntext mContext;
public NonActivityClass(Context context)
{
mContext =context;
}
Then
Toast.makeText(mContext, "Button is clicked", Toast.LENGTH_LONG).show();
Note : Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself) to avoid memory leaks.
如果您想从课堂上敬酒,则应将上下文发送给您的课堂。
It`s matter of context value not to worry.
Instead of using getApplicationContext()
use Activityname.this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.