Android中回調接口的使用介紹
更新時間:2013年06月17日 16:40:49 作者:
回調接口在完成某些特殊的功能時還是蠻有用的,下面為大家分享下具體的使用方法,感興趣的朋友可以參考下哈
MainActivity如下:
package cn.testcallback;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
/**
* Demo描述:
* Android中回調接口的使用
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
for (int i = 0; i < 10000; i++) {
if (i == 9527) {
showToast(i, new CallBackInterface() {
@Override
public void callBackFunction(int i) {
Toast.makeText(MainActivity.this, "我的編號:"+i, Toast.LENGTH_LONG).show();
}
});
}
}
}
//定義函數(shù),其中一個參數(shù)為CallBackInterface類型
private void showToast(int i, CallBackInterface callBackInterface) {
callBackInterface.callBackFunction(i);
}
//定義接口.且在接口中定義一個方法
public interface CallBackInterface {
public void callBackFunction(int i);
}
}
main.xml如下:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_centerInParent="true"
/>
</RelativeLayout>
復制代碼 代碼如下:
package cn.testcallback;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
/**
* Demo描述:
* Android中回調接口的使用
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
for (int i = 0; i < 10000; i++) {
if (i == 9527) {
showToast(i, new CallBackInterface() {
@Override
public void callBackFunction(int i) {
Toast.makeText(MainActivity.this, "我的編號:"+i, Toast.LENGTH_LONG).show();
}
});
}
}
}
//定義函數(shù),其中一個參數(shù)為CallBackInterface類型
private void showToast(int i, CallBackInterface callBackInterface) {
callBackInterface.callBackFunction(i);
}
//定義接口.且在接口中定義一個方法
public interface CallBackInterface {
public void callBackFunction(int i);
}
}
main.xml如下:
復制代碼 代碼如下:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_centerInParent="true"
/>
</RelativeLayout>
相關文章
Android 超詳細深刨Activity Result API的使用
這篇文章主要介紹了Android開發(fā)中Activity Result API的使用,掌握了它以后你就可以放棄startActivityForResult了,感興趣的朋友一起來看看吧2022-03-03android自定義控件ImageView實現(xiàn)圓形圖片
這篇文章主要為大家詳細介紹了android自定義控件ImageView實現(xiàn)圓形圖片,適用于用戶頭像,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12Android?妙用TextView實現(xiàn)左邊文字,右邊圖片
這篇文章主要介紹了Android?妙用TextView實現(xiàn)左邊文字,右邊圖片的相關資料,需要的朋友可以參考下2023-07-07