Android如何创建一个自定义回调接口(例1)

1.创建一个回调的接口

首先,在回调接口中添加几个回调方法,如下

public interface MyCallBack {
    /**
     * 调用加法的回调
     * @param res 结果
     * @param isPositive 是否是正数
     */
    void onPlus(int res,boolean isPositive);

    /**
     * 调用减法的回调
     * @param res 结果
     * @param isPositive 是否是正数
     */
    void onSubtract(int res,boolean isPositive);

}

2.创建MyAPI类,用于提供相关的API接口。

代码如下:

public class MyAPI {
    private final String TAG = "MySDK";
    private ArrayList<MyCallBack> callBackList = new ArrayList<>();

    public MyAPI(){

    }
    /**
     * 添加回调
     * 用于将上层实现的回调接口传到自定义的API中。	  
     * @param callBack
     */
    public void addCallback(MyCallBack callBack){
        callBackList.add(callBack);
        Log.i(TAG, "addCallback: ");
    }
    /**
     * 移除回调
     * @param callBack
     */
    public void removeCallback(MyCallBack callBack){
        callBackList.remove(callBack);
        Log.i(TAG, "removeCallback: ");
    }
    /**
     * 加法
     * 通过迭代遍历上层传进来的回调接口的集合中的美哟个对象,然后通过该对象
     * 来调用接口中的方法,将参数传入到接口中,这样在上层调用API中的方法时
     * 就可触发回调,在回调中获取传入的值。		
     * @param a
     * @param b
     */
    public void plus(int a, int b){
        int sum = a + b;
        for (MyCallBack callBack:callBackList) {
                callBack.onPlus(sum,((sum>=0)?true:false));
        }
        Log.i(TAG, "plus: a:"+a+",b:"+b);
    }

    /**
     * 减法
     * 通过迭代遍历上层传进来的回调接口的集合中的美哟个对象,然后通过该对象
     * 来调用接口中的方法,将参数传入到接口中,这样在上层调用API中的方法时
     * 就可触发回调,在回调中获取传入的值。
     * @param a
     * @param b
     */
    public void subtract(int a,int b){
        int sub = a - b;
        for (MyCallBack callBack:callBackList) {
            callBack.onSubtract(sub,((sub>=0)?true:false));
        }
        Log.i(TAG, "subtract: a:"+a+",b:"+b);
    }

    /**
     * 获取当前callbacks的数量
     */
    public int  getCallbackSize() {
        int size = callBackList.size();
        Log.i(TAG, "getCallbackSize: current CallbackSize :"+size);
        return size;
    }
}

3.在MainActivity中创建测试API和回调

首先在MainActivity中实现MyCallBack接口,通过API的对象来调用API中添加回调的方法,之后再调用API中的计算的方法,即可在重写的回调方法中收到回调的数据。
代码如下:

public class MainActivity extends AppCompatActivity implements MyCallBack {
private TextView tv_info;
private EditText et_num1,et_num2;
private MyAPI mySDK;
private  String str = "";
private final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mySDK = new MyAPI();
    }
    private void initView(){
        tv_info  = findViewById(R.id.tv_info);
        et_num1 = findViewById(R.id.et_num1);
        et_num2 = findViewById(R.id.et_num2);
    }
    @Override
    public void onPlus(int res, boolean isPositive) {
        Log.i(TAG, "onPlus: res:"+res+",isPositive:"+isPositive);
        System.out.println("onPlus:res="+res+","+(isPositive?"正数":"负数"));
        str = str+"onPlus:res="+res+","+(isPositive?"正数":"负数")+"\n";
        tv_info.setText(str);
    }

    @Override
    public void onSubtract(int res, boolean isPositive) {
        Log.i(TAG, "onSubtract: res:"+res+",isPositive:"+isPositive);
        System.out.println("onSubtract:res="+res+","+(isPositive?"正数":"负数"));
        str = str+"onSubtract:res="+res+","+(isPositive?"正数":"负数")+"\n";
        tv_info.setText(str);
    }

    public void onAddCallback(View view) {
        //上层调用添加回调接口
        mySDK.addCallback(this);
        int callbackSize = mySDK.getCallbackSize();
        Toast.makeText(this, "CurrentCallbackSize:"+callbackSize, Toast.LENGTH_SHORT).show();
    }
    public void onRemoveCallback(View view) {
        //上层调用移除回调接口
        mySDK.removeCallback(this);
        int callbackSize = mySDK.getCallbackSize();
        Toast.makeText(this, "CurrentCallbackSize:"+callbackSize, Toast.LENGTH_SHORT).show();
        //如果回调集合大小<=0,则置空文本
        if (mySDK.getCallbackSize()<=0){
            tv_info.setText("");
        }
    }
    public void onplus(View view) {
        str = "";
        int a = Integer.valueOf(et_num1.getText().toString());
        int b = Integer.valueOf(et_num2.getText().toString());
        int callbackSize = mySDK.getCallbackSize();
        /*检测当前是否有回调*/
        if (callbackSize>0){
            mySDK.plus(a,b);
        }else{
            Toast.makeText(this, "请先添加回调!", Toast.LENGTH_SHORT).show();
        }
    }

    public void onSub(View view) {
        str = "";
        int a = Integer.valueOf(et_num1.getText().toString());
        int b = Integer.valueOf(et_num2.getText().toString());
        int callbackSize = mySDK.getCallbackSize();
        /*检测合法性*/
        if (callbackSize>0){
            mySDK.subtract(a,b);
        }else{
            Toast.makeText(this, "请先添加回调!", Toast.LENGTH_SHORT).show();
        }

    }
}

界面的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="num1" />
        <EditText
            android:id="@+id/et_num1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_weight="1"
            android:hint="输入num1"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="num2" />
        <EditText
            android:id="@+id/et_num2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_weight="1"
            android:hint="输入num2"/>

    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:onClick="onAddCallback"
            android:text="添加回调" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:onClick="onRemoveCallback"
            android:text="删除回调" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:onClick="onplus"
            android:text="相加" />
        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:onClick="onSub"
            android:text="相减" />
    </LinearLayout>

    <TextView
        android:id="@+id/tv_info"
        android:layout_width="match_parent"
        android:background="#DDDADA"
        android:layout_height="wrap_content" />
</LinearLayout>	

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值