回调callback
程序员文章站
2022-07-04 10:23:40
...
title: 回调callback
参考:
JAVA回调机制(CallBack)详解
一个经典例子让你彻彻底底理解java回调机制
1.新建一个类,声明接口:
public interface GetCodeCallback {
void GetCodeCallback(String result);
}
2.实现接口
public abstract class AbstractBlocklyActivity extends AppCompatActivity implements GetCodeCallback{
@Override
public void GetCodeCallback(String result) {
System.out.println("返回来的*--->" + result);
}
在oncreate 中使用
LoggingCodeGeneratorCallback lc = new LoggingCodeGeneratorCallback(this,"我也不知道");
lc.executeMessage(this);
public class LoggingCodeGeneratorCallback implements CodeGenerationRequest.CodeGeneratorCallback {
private static GetCodeCallback callbackd; //使用静态,不然会是空指针异常。
protected final String mTag;
protected final Context mContext;
public LoggingCodeGeneratorCallback(Context context, String loggingTag) {
mTag = loggingTag;
mContext = context;
}
public void executeMessage(GetCodeCallback callBack) {
System.out.println("小王问的问题--->");
this.callbackd = callBack;
}
@Override
public void onFinishCodeGeneration(String generatedCode) {
// Sample callback.
if (generatedCode.isEmpty()) {
Toast.makeText(mContext,
"Something went wrong with code generation.", Toast.LENGTH_LONG)
.show();
} else {
Log.d(mTag, "code: " + generatedCode);
// Toast.makeText(mContext, generatedCode, Toast.LENGTH_LONG).show();
callbackd.GetCodeCallback(generatedCode);
}
}
}
上一篇: 回调函数——callback
下一篇: 回调函数callback…………
推荐阅读