开发者

How to create a Toast from a class

I have a new project - MyProject. In that project I have the class MyProject and another class uTorrent. How do I show a toast from the uTorrent class? When I try this:

Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);

I get this error:

The method getApplicationContext() is undefined for the type uTor开发者_高级运维rent

Thanks


The post seems to be old, but I'm posting this answer in case someone is having the same issue

Answer:

You need to extend the class, as follows:

package HelloAndroid.workspace;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

public class myClass **extends Activity**{

......

}


You need to pass a Context into the class you're using the Toast.


What you can do is make a public function in you activity like this :

in Activity.Class :

public void makeToast(String message) {
    Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
}

then call from uTorrent.class :

activity.makeToast(e.getMessage());

But it suppose you gave the activity as a parameter to uTorrent.


Are you calling this from an Activity? It would help to see some code, but what you need is a Context. This will typically be your Activity or Application class.


Try to give the class a Context variable with the context where you want to show the Toast.

Anyway i guess that djg have the correct answer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜