接口回调是指:可以把使用某一接口的类创建的对象的引用赋给该接口声明的接口变量,那么该接口变量就可以调用被类实现的接口的方法。实际上,当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,这一过程称为对象功能的接口回调。
做个笔记插个代码:
主页代码:
public class CallBackActivity extends Activity {
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initId();
}
public void initId() {
tv = (TextView) findViewById(R.id.tv);
}
public void clickbtn(View view){
Utils utils = new Utils();
utils.setCallBack(interfDemo);
utils.show();
}
CallbackIntef interfDemo = new CallbackIntef() {
public void start(String data) {
// TODO Auto-generated method stub
showToast(data);
}
public void progerss(String data) {
// TODO Auto-generated method stub
showToastOnUi(data);
}
public void fail(String data) {
// TODO Auto-generated method stub
showToastOnUi(data);
}
public void end(String data) {
// TODO Auto-generated method stub
showToastOnUi(data);
}
};
public void showToast(String data) {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
public void showToastOnUi(final String data) {
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG)
.show();
}
});
}
}
工具类代码:
public class Utils {
private static CallbackIntef callback;
public void setCallBack(CallbackIntef callback) {
this.callback = callback;
}
public void show() {
callback.start("哈哈,我开始啦");
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
callback.progerss("正在进行中!!!");
Thread.sleep(3000);
callback.end("哈哈哈,已经结束了!!!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
callback.fail("不好意思,失败了!!!");
}
}
}).start();
}
}
还有接口的:
public interface CallbackIntef {
public void start(String data);
public void progerss(String data);
public void fail(String data);
public void end(String data);
}
个人觉得这个demo很简单很容易看懂.很适合新手理解.
如果有更好的接口回调的demo求贴出来,让我涨涨见识