Android中回调接口使用实例

时间:2022-11-26 05:30:08

MainActivity如下:

package cc.cn;

import cc.cn.ThreadSubclass.YourListener;
import android.app.Activity;
import android.os.Bundle;
/**
* Demo描述:
* Android中回调接口使用实例
*/
public class MainActivity extends Activity {
private ThreadSubclass mThreadSubclass;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}

private void init(){
mThreadSubclass=new ThreadSubclass();
mThreadSubclass.setYourListener(new YourListener() {
@Override
public void onSomeChange(String info,int i) {
System.out.println("------> info="+info);
System.out.println("------> i="+i);
}
});
mThreadSubclass.start();
}

}

ThreadSubclass如下:

package cc.cn;

public class ThreadSubclass extends Thread {
private YourListener mYourListener=null;

@Override
public void run() {
super.run();
for (int i = 0; i < 5; i++) {
System.out.println("Now is "+i);
}
if (mYourListener!=null) {
mYourListener.onSomeChange("输入已经完毕",9527);
}
}

//回调接口(监听器)
public interface YourListener {
public void onSomeChange(String info,int i);
}

//设置回调接口(监听器)的方法
public void setYourListener(YourListener yourListener) {
mYourListener = yourListener;
}



}

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android中回调接口使用实例"
android:layout_centerInParent="true" />


</RelativeLayout>