[英]Android Calling Method in Activity Class
I have java class called Second.java which has a method called toast_method(). 我有一个名为Second.java的Java类,它具有一个名为toast_method()的方法。 My question is, How can i call the toast_method() from the Second.java and then display the toast message in the app? 我的问题是,如何从Second.java调用toast_method(),然后在应用程序中显示Toast消息?
I tried the following code but it's not working 我尝试了以下代码,但无法正常工作
Second.java 第二.java
package com.example.callmethod;
import android.content.Context;
import android.widget.Toast;
public class Second {
Context context;
public Second(Context context) {
this.context = context;
}
public void toast_method() {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
}
MainActivity.java MainActivity.java
package com.example.callmethod;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
private Second myotherclass;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass.toast_method();
}
}
Thanks 谢谢
You are nearly there! 你快到了! Only missing the vital instantiation of the second class: 仅缺少第二类的重要实例:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass = new Second(this); // <----- this
myotherclass.toast_method();
}
do it in onCreate Like this 像这样在onCreate中完成
Second second =new Second(this);
second.toast_method();
Easy one ^^ 简单的一个^^
you have to extends Activity to use context in the activity 您必须扩展活动以在活动中使用上下文
public class operation extends Activity {
// normal toast
//you can change length
public static void toast(String toastText, Context contex) {
Toast.makeText(contex, toastText, Toast.LENGTH_LONG).show();
}
// Empty Toast for Testing
public static void emptyToast(Context contex) {
Toast.makeText(contex, R.string.EmptyText, Toast.LENGTH_LONG).show();
}
}
now ... in your activity only call function 现在...在您的活动中仅调用函数
operation.toast("Your Text",currentClass.this);
Example : 范例:
public class currentClass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
operation.toast("Hello",currentClass.this);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.