回调机制在java中应用非常广泛,下面用一个demo简单的实现回调机制
1.Time.java
package com.test;
public class Time {
private OnTimeChange mOnTimeChange;
private int time;
/*接口*/
public interface OnTimeChange{
public void timChange();
}
/*监听事件*/
public void setOnTimeChangeListener(OnTimeChange change){
mOnTimeChange=change;
}
public void setTime(int value){
time=value;
mOnTimeChange.timChange();
}
}
2.Caller.java
public class Caller extends Activity implements OnTimeChange {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Time time=new Time();
time.setOnTimeChangeListener(this);//监听事件
time.setTime(1);
/*匿名内部类实现接口*/
time.setOnTimeChangeListener(new OnTimeChange() {
@Override
public void timChange() {
// TODO Auto-generated method stub
Log.i("debug", "time has changed");
}
});
}
@Override
public void timChange() {
// TODO Auto-generated method stub
Log.i("debug", "Time has changed");
}
}