简体   繁体   English

吐司在主要活动中效果很好,但在课堂上却不行

[英]Toast works fine in main Activity but not in a class

Using Toast in the MainActivity works fine MainActivity使用Toast可以正常工作

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. 但是当我在类中使用它时, getApplicationContext()会变成红线,并且不起作用。 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 您需要将上下文从Activity传递到非Activity类,并在那里使用相同的上下文

  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 代替使用getApplicationContext()使用Activityname.this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM