Android中回調接口使用實例

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如下:



    
    

發佈留言