android如何创建自己的监听接口.doc
文本预览下载声明
android如何创建自己的监听接口
第一步:创建接口和方法
public interface OnUsernameAvailableListener {
public abstract void onAvailableChecked(String username, boolean available);
}
第二步:定义变量保存listener
OnUsernameAvailableListener onUsernameAvailableListener = null;
第三步:提供方法允许用户设置Listener
// Allows the user to set an Listener and react to the event
public void setOnUsernameAvailableListener(OnUsernameAvailableListener listener) {
onUsernameAvailableListener = listener;
}
第四步:提供方法允许用户获得Listener
public final OnUsernameAvailableListener getOnUsernameAvailableListener() {
return onUsernameAvailableListener;
}
第五步:添加方法,此方法每次在监听事件被触发的时候调用
// This function is called after the check was complete
private void OnUserChecked(String username, boolean available){
// Check if the Listener was set, otherwise well get an Exception when we try to call it
if(onUsernameAvailableListener!=null) {
// Only trigger the event, when we have a username
if(!TextUtils.isEmpty(username)){
onUsernameAvailableListener.onAvailableChecked(username, available);
}
}
}
完成。
附完整代码:
package com.tseng.examples;
import com.tseng.examples.CheckUsernameEditText.OnUsernameAvailableListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterExample extends Activity {
// Declare our Views, so we can access them later
private CheckUsernameEditText etUsername;
private EditText etPassword;
private EditText etPassword2;
private Button btnRegister;
private Button btnCancel;
private TextView lblUserStatus;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set Activity Layout
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername =
显示全部