Java 如何展示非活动课程的祝酒词
我想调用一个函数,该函数在showtoast类中显示toast消息,该类从非活动类database类扩展活动。但这是一个明显的错误 我该怎么做Java 如何展示非活动课程的祝酒词,java,android,Java,Android,我想调用一个函数,该函数在showtoast类中显示toast消息,该类从非活动类database类扩展活动。但这是一个明显的错误 我该怎么做 public class database { showtoast objshowtoast = new showtoast(); objshowtoast.toast (); } public class showtoast extends Activity { protected void onCreate() {
public class database {
showtoast objshowtoast = new showtoast();
objshowtoast.toast ();
}
public class showtoast extends Activity {
protected void onCreate() {
}
public toast() {
Toast.makeText(showtoast.this, "hi toast executed!!", Toast.LENGTH_LONG).show();
}
}
这应该是公开的
如果没有返回类型,它将被解释为构造函数
此外,您不能使用新的创建活动
您必须通过对当前活动使用方法来创建意图和活动
// 'this' is the current activity
this.startActivity(intent);
嗯,你发布的代码有很多问题,但我没有涉及这些问题。如果手头的任务只是显示非活动类的toast,那么您不需要为此创建活动
您只需要引用应用程序上下文并将其传递给创建toast。您可以将应用程序上下文作为构造函数参数传递给您的非活动类。为什么不将上下文与构造函数一起传递? 像 编辑 您可以在showtoast中这样编写toast方法 从活动中调用此项,如 烤面包片展示烤面包片 和来自数据库类 showtoots.toast\u mContext
我建议你不要用一种方法来展示祝酒词。它只是一行代码。为什么需要一个方法来实现此目的?它显示了什么错误?请选择system.out.println或在constutor或中传递上下文so@adcom系统退出?如果你需要的话,最好记录.d。无论如何,你不能直接创建活动,因为它没有上下文。请遵循Android的代码风格:你应该接受帮助你的答案。为什么你需要ApplicationContext来制作Toast?没有必要。您需要一个上下文,如果您试图从活动中显示toast,请使用它的上下文,否则,如果您是从后台显示toast,则必须使用应用程序上下文。请检查下面的答案。是的,这就是我的意思。谢谢你把它转换成代码。
public class database {
Context _mContext;
public database(Context c)
{
_mContext = c;
}
Toast.makeText(_mContext, "Hello Android", 100).show();
}
public class showtoast extends Activity {
protected void onCreate() {
database db = new database(showtoast.this); // calling the constructor and passing the context.
}
public toast() {
Toast.makeText(showtoast.this, "hi toast executed!!", Toast.LENGTH_LONG).show();
}
}
public static void toast(Context c)
{
Toast.makeText(c, "Hello Toast is displaying", 100).show();
}