1.相关知识
先看看使用Button的过程。
通过调用 public voidsetOnClickListener (View.onClickListener l) 来设置回调函数。
当执行按下按钮时,按钮会调用这个函数。
2. 实现步骤
1. 定义接口
2. 定义为需要的类A添加该接口及相应的方法
3. 在实现类A中的类B中实现该方法。
3. 示例:
(1) 接口文件:
MyCallback.java
package com.interfacetest;
public interface MyCallback {
public void run(String content);
}
(2) 使用接口的类
MyView.java
package com.interfacetest;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyView extends TextView {
private MyCallback myCallback;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
new myThread().start();
}
/** 调用这个函数来初始化接口,就像Button的setOnClickListener */
public void setMyCallback(MyCallback myCallback) {
this.myCallback = myCallback;
}
/** 对调用接口函数操作的封装 */
public void callMycallback(String content) {
myCallback.run(content);
}
class myThread extends Thread {
private int count = -1;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
/** 调用接口函数 */
callMycallback(count + "");
}
}
}
(3) 实现回调方法
MainActivity.java
package com.interfacetest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyView myView = (MyView) findViewById(R.id.myView);
myView.setMyCallback(new MyCallback() {
@Override
public void run(String content) {
// TODO Auto-generated method stub
System.out.println("=== content:" + content + " ===");
}
});
Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
})
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}