在外部类使用吐司 [英] Using Toast in a external class

查看:135
本文介绍了在外部类使用吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从谁延伸活动之一除了控制我的应用程序逻辑的类,它的这最后一个内部声明。

我想知道是否有使用敬酒该类上的方法。

我试图扩大与活动的类,并在他的构造函数发送的背景下,但没有奏效。

编辑:

在这里,你有我如何通过在构造背景下code:

  GameController newgame =新GameController(getApplicationContext());公共GameController(上下文_context)
{
    // ...
    上下文= _context;
}Toast.makeText(背景下,你不能赌这个数额,最低限度的办法是:+ minimun_bet,2).show();

当我运行此我得到这个错误:

  10月5日至29日:58:06.230:E / AndroidRuntime(5753):了java.lang.RuntimeException:无法内螺纹已不叫尺蠖$ P $创建处理程序ppare()


解决方案

吐司只需要使用上下文来显示。所有你需要做的是上下文传递给这个类,这一切将被罚款。我做这一切的一切我的自定义类的时间。如果你可以分享你如何实现/调用构造函数传递这个背景下,我们可以帮助指出。

基本上,它是这样的:

 公共MyClass的{
    私人上下文的背景下;
    公共MyClass的(上下文的背景下){
        this.context =背景;
    }
    私人无效警报(弦乐味精){
        Toast.makeText(this.context,味精,Toast.LENGTH_LONG).show();
    }
}

现在,你想要做的是检查,看看是否这方面是有效还是无效,当你传递进去。有这么多的情况下,当我不小心用getBaseContext而不是getApplicationContext和事业的问题。但实际上,你可以通过你的活动中,并投它的上下文没有任何问题。

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()

解决方案

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.

这篇关于在外部类使用吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆