接口回调、监听
以我自己写的demo中的OnExposureChangeListener(曝光监听)为例去解析下接口回调这个Andrid常见的数据交互方式。
理解:当调用声明的接口引用的抽象方法时,实际上调用的是实现了接口的类对应的具体方法(或者匿名的方式实现接口的具体方法)
一、回调必有的四要素:
1.回调的接口,该接口一般在使用的类里面创建或者单独创建
2.在使用的类中接口的定义变量(接口不可以实例化)
3.一个给接口变量赋值的方法
4.该类中定义的接口变量的使用的场景
实例讲解:
//FocusSunView是一个聚焦框的自定义view
public class FocusSunView extends View {
//对应2:接口变量
private OnExposureChangeListener onExposureChangeListener;
//对应1:创建的回调接口,以及接口中要做的事
public interface OnExposureChangeListener {
//当move事件时,view的滑杆变化,然后拿到对应的滑杆值去设置曝光
void onExposureChange(float exposure);
}
//对应3:设置曝光回调监听
public void setOnExposureChangeListener(OnExposureChangeListener onExposureChangeListener){
this.onExposureChangeListener = onExposureChangeListener;
}
//对应4:一个使用接口变量的地方
@Override
public boolean onTouchEvent(MotionEvent event) {
…………
//使用前需要先判断监听是不是为空
if (onExposureChangeListener != null && oldExposure != exposure) {
oldExposure = exposure;
onExposureChangeListener.onExposureChange(exposure);//可以看到我在这里set了一个exposure的值,那么我在具体实现方法那里就可以拿到用了,这其实就是那些监听最后拿到的状态码是一样的
}
……………
}
}
二、具体实现回调的接口的类:
在具体回调实现的类中,一般是实例化使用类的对象,在具体实现的类中采取接口的变量赋值,以及接口的具体实现方法,正式这样综合实现了接口和具体的实现分离,从而达到回调效果,具体也是三大要素
1.使用接口类实例的引用
2.引用的对象实现对接口的变量的传递
3.引用的对象对接口的使用
本demo实现的方法是采用匿名的方式实现接口的具体方法
public class Camera2Basic extends Fragment {
//对应1:FocusSunView类的实例的引用
private FocusSunView focusSunView;
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
………………
focusSunView.setOnExposureChangeListener(new FocusSunView.OnExposureChangeListener() {
@Override
public void onExposureChange(float exposure) {
Log.e(TAG, "FocusSunView onExposureChangeListener: -----------> exposure:"+exposure);
//TODO 曝光调整
//在这里我只是注册了监听,当FocusSunView那边调用时,我就会接收到值,就用条杆拿到的值去调整iso,达到相应变化
//具体实现接口的方法
setIsoChange((int)exposure);
}
});
………………
}
总结如下:
- FocusSunView类中有一个接口变量和接口。
- Camera2Basic类实现FocusSunView类的接口(这个接口就是所谓的回调接口)。
- FocusSunView类的接口变量会(通过过某种方法)获得靠Camera2Basic类实现的接口。
- FocusSunView类在一个适当的时机“使用”这个接口变量,即调用接口中的函数(这个函数就是所谓的回调函数)。