用于Interface
将事件发送回活动并在收到事件时更新列表或数据库。
接口是将消息传递到“外部世界”的方式。只看一个简单的button onClickListener
。您基本上setOnClickListener(this)
在按钮上调用 a 并实现onClickListener
,这是 a interface
here。每当单击按钮时,您都会在onClick
. 这是在不需要意图的情况下在活动之间传递消息的最安全方式(在我看来,这是一个巨大的痛苦......)这是一个例子:
例子:
class A extends Activity implements EventInterface{
public A(){
//set a listener. (Do not forget it!!!)
//You can call it wherever you want;
//just make sure that it is called before you need something out of it.
//safest place is onCreate.
setEventInterfaceListener( A.this );
}
//this method will be automatically added once you implement EventInterface.
void eventFromClassB(int event){
//you receive events here.
//Check the "event" variable to see which event it is.
}
}
class B{
//Interface logic
public interface EventInterface{
public static int BUTTON_CLICKED = 1;
void eventFromClassB(int event);
}
static EventInterface events;
public static void setEventInterfaceListener(EventInterface listener) {
events = listener;
}
private void dispatchEvent(int trigger) {
if (events != null) {
events.eventFromClassB(trigger);
}
}
//Interface ends
void yourMethod(){
//Call this whenever you want to send an event.
dispatchEvent( BUTTON_CLICKED );
}
}