Using Toast in a external class

我怕爱的太早我们不能终老 提交于 2019-12-11 19:49:46

问题


I have a class that controls my app logic apart from the one who extends Activity, and its declared inside this last one.

I would like to know if there is a way to use toast on that class.

I tried extending that class with Activity and sending the context in his constructor but it didn't work.

EDIT:

Here you have the code of how I pass the context in the constructor:

GameController newgame = new GameController(getApplicationContext());

public GameController(Context _context)
{       
    //...       
    context = _context;
}

Toast.makeText(context, "You can't bet this amount, the minimun bet is: " + minimun_bet, 2).show();

When I run this I get this error:

05-29 10:58:06.230: E/AndroidRuntime(5753): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

回答1:


Toast only need to use Context to show. All you need to do is pass the Context to this class and it all will be fine. I do this all the time for all of my custom class. If you could share how you implement/call this passing Context in constructor, we could help pointing out.

Basically, it's something like this:

public MyClass{
    private Context context;
    public MyClass(Context context){
        this.context = context;
    }
    private void alert(String msg){
        Toast.makeText(this.context, msg, Toast.LENGTH_LONG).show();
    }
}

Now, what you wanna do is checking to see if that Context is valid or not when you pass into it. There's so many instances when I accidentally use getBaseContext instead of getApplicationContext and that cause problem. But in fact, you can just pass your Activity in and cast it as Context without any problem.




回答2:


public class ClassName {        
    public ClassName(Activity _activity) {
            Toast.makeText(_activity, "text", Toast.LENGTH_LONG).show();
    }
}

you can use it as ClassName(YourActivity.this);




回答3:


The class should not need to be extended from Activity, but you would need to somehow pass it a context to use. This could be an Activity context or the Application context.

Just make sure it does not hold onto the context forever.




回答4:


Try this it worked for me

In your Activity

Context context= new yourclass().getAndSetMyContext(Activity.this);

In your Class private static Context c;

public  Context getAndSetMyContext(Context c) {
    this.c = c;
    return this.c;
}

in Method where you need the Toast just use

Toast.makeText(c,message,Toast.LENGTH_SHORT).show();



来源:https://stackoverflow.com/questions/10787940/using-toast-in-a-external-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!