在 IOS 中,当我们想要在特定情况发生时处理一个 Action 时,我们使用 block
。
Android 中是否有这样的方法来处理 onCompletion 情况,我们可以在任何地方添加。
与AsyncTask 方法一样,它知道工作何时完成。它执行 onPostExecute。当特定情况发生时,我们如何创建这种类型的方法,我们如何处理它。
今天我找到了一种在 IOS 中表现得像 block 的方法
BaseAsyncTask(new Callback(){
onPostResult(string result)
{
// do whatever you want to do with the result got from asynctaks
}
});
它是一个委托(delegate),它会在遇到特定情况时调用..
上面的代码是 android 中的 block ,就像我们在 IOS 中所做的那样,我说得对吗?或者有任何其他方式在 android 中创建 block 。
最佳答案
表现得像 iOS block :
一个。比方说,在你的类 APISingleton 中(例如单例类中的 Volley request-API):
在类外定义接口(interface):
// Callback Blueprint interface APICallback { void onResponse(User user, boolean success, String message); // Params are self-defined and added to suit your needs. }
在您的 API 请求函数中
public void requestAPIWithURL:(String url, final APICallback callback) { // .... // After you receive your volley response, // Parse the JSON into your model, e.g User model. callback.onResponse(user, true, "aloha"); }
B.因此,如何调用 API 请求并从您的 Activity 或 fragment 传递回调函数,如下所示:
APISingleton.getInstance().requestAPIWithURL("http://yourApiUrl.com", new APICallback() {
@Override
public void onResponse(User user, boolean success, String message) {
// you will get your user model, true, and "aloha" here
mUser = user;
Log.v(TAG, "success:" + success);
Log.v(TAG, "aloha or die?" + message);
// Your adapter work. :D
}
});
关于android - 如何在android中实现 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115711/