gpt4 book ai didi

android - 如何在 Activity 形式非 Activity 类中调用方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:51:21 25 4
gpt4 key购买 nike

我有一个 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);
}
}

最佳答案

只需在 DateClass 中创建一个回调接口(interface)即可。

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

}
}

关于android - 如何在 Activity 形式非 Activity 类中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com