Android中回调接口的使用
MainActivity如下:
package cn.testcallback; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * Android中回调接口的使用 */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); testCallBack(); } private void testCallBack(){ AskQuestion askQuestion=new AskQuestion(); String questionString="Do you love me ?"; System.out.println("The question is : "+questionString); askQuestion.askQuestion(questionString); } }
CallBackInterface如下:
package cn.testcallback; /** * 定义一个接口 * 接口中有一方法 */ public interface CallBackInterface { public void answerQuestion(String result); }
AskQuestion如下:
package cn.testcallback; public class AskQuestion implements CallBackInterface{ public void askQuestion(final String questionString){ new Thread(){ public void run() { AnswerQuestion answerQuestion=new AnswerQuestion(); answerQuestion.receiveQuestion(AskQuestion.this, questionString); }; }.start(); } @Override public void answerQuestion(String result) { System.out.println("The answter is : "+result); } }
AnswerQuestion如下:
package cn.testcallback; public class AnswerQuestion { public void receiveQuestion(CallBackInterface callBackInterface,String questionString){ try { Thread.sleep(3000); } catch (Exception e) { } String result="YES!!!"; callBackInterface.answerQuestion(result); } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="回调的使用" android:layout_centerInParent="true" /> </RelativeLayout>