欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

回调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);
        }
    }
}