我有一个Activity和非Activity类。如何从非Activity类
调用Activity类中的方法public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
DataClass dc = new DataClass();
dc.show();
}
public void call(ArrayList<String> arr) {
// Some code...
}
}
public class DataClass {
public void show(ArrayList<String> array) {
// Here I want to send this ArrayList values into the call
// method in activity class.
MainActivity act = new MainActivity();
act.call(array);
}
}
答案 0 :(得分:14)
只需在DateClass中创建一个回调接口。
public DateClass {
public interface IDateCallback {
void call(ArrayList<String> arr);
}
private IDateCallback callerActivity;
public DateClass(Activity activity) {
callerActivity = (IDateCallback)activity;
}
...
}
public void show(ArrayList<String> array) {
callerActivity.Call(array);
...
}
//And implements it inside your activity.
public class MainActivity extends Activity
implements IDateCallback {
public void call(ArrayList<String> arr) {
}
}
答案 1 :(得分:6)
你可以做几件事。我认为最简单的方法是将Context
发送到DataClass
,如下所示:
DataClass dc =new DataClass();
dc.show(this);
在您的DataClass
中将上下文保存为全局var Context context
。然后像这样使用它:
((MainActivity)context).call(array);
答案 2 :(得分:2)
((MainActivity)getContext).array();
答案 3 :(得分:0)
只需制作一个单身:
TeacherDashboardSingleton:
public class TeacherDashboardSingleton {
public Teacher_Dashboard aa;
private static final TeacherDashboardSingleton ourInstance = new TeacherDashboardSingleton();
public static TeacherDashboardSingleton getInstance() {
return ourInstance;
}
}
myActivity类:
onCreate(....){
....
TeacherDashboardSingleton.getInstance().aa = this;
....
}
这将创建与活动
中相同实例的对象现在你可以在任何地方使用它