欢迎来到天天文库
浏览记录
ID:37917713
大小:40.00 KB
页数:5页
时间:2019-06-02
《android如何创建自己的监听接口》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、android如何创建自己的监听接口第一步:创建接口和方法publicinterfaceOnUsernameAvailableListener{publicabstractvoidonAvailableChecked(Stringusername,booleanavailable);}第二步:定义变量保存listenerOnUsernameAvailableListeneronUsernameAvailableListener=null;第三步:提供方法允许用户设置Listener//AllowstheusertosetanListenerandre
2、acttotheeventpublicvoidsetOnUsernameAvailableListener(OnUsernameAvailableListenerlistener){onUsernameAvailableListener=listener;}第四步:提供方法允许用户获得ListenerpublicfinalOnUsernameAvailableListenergetOnUsernameAvailableListener(){returnonUsernameAvailableListener;}第五步:添加方法,此方法每次在监听事件被触
3、发的时候调用//ThisfunctioniscalledafterthecheckwascompleteprivatevoidOnUserChecked(Stringusername,booleanavailable){//CheckiftheListenerwasset,otherwisewe'llgetanExceptionwhenwetrytocallitif(onUsernameAvailableListener!=null){//Onlytriggertheevent,whenwehaveausernameif(!TextUtils.isE
4、mpty(username)){onUsernameAvailableListener.onAvailableChecked(username,available);}}}完成。附完整代码:packagecom.tseng.examples;importcom.tseng.examples.CheckUsernameEditText.OnUsernameAvailableListener;importandroid.app.Activity;importandroid.graphics.Color;importandroid.os.Bundle;im
5、portandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.TextView;publicclassRegisterExampleextendsActivity{//DeclareourViews,sowecanaccessthemlaterprivateCheckUsernameEditTextetUsername;private
6、EditTextetPassword;privateEditTextetPassword2;privateButtonbtnRegister;privateButtonbtnCancel;privateTextViewlblUserStatus;/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);//SetActivityLayoutsetCon
7、tentView(R.layout.main);//GettheEditTextandButtonReferencesetUsername=(CheckUsernameEditText)findViewById(R.id.username);etPassword=(EditText)findViewById(R.id.password);etPassword2=(EditText)findViewById(R.id.password2);btnRegister=(Button)findViewById(R.id.register_button);bt
8、nCancel=(Button)findViewById(R.id.cancel_button);lblUs
此文档下载收益归作者所有