Android Custom Event

和自甴很熟 提交于 2019-12-13 00:19:28

问题


I am new to Android and Java development and am looking to implement a custom event, however having done lots of research and trying various different approaches i cannot seem to get it to work.

I am essentially trying to create a battle system, which i have implemented in .NET but cannot seem to get working in Java, it requires me to create events for things such as DealtDamage, DamageReceived, Died etc.

This will be inherteing information from the characters object which consits of thing such as hp, attack, defence etc.

Can someone please provide sample code how I can create these events and then action them in various classes.

e.g. Damage Dealt

user1 atk - user 2 def = totalatk return totalatk

Thanks


回答1:


If you are trying to generate callbacks from your class (raise events):

In the class which generates the callback:

public interface EventHappened{
        void callback(int arg1, String arg2);
}

...

ArrayList<EventHappened> eventHappenedObservers = new ArrayList<~>;

...

public void setEventHappenedObserver(EventHappened observer){
     eventHappenedObservers.add(observer);
}

...

if (eventHasHappened){
    for (EventHappened eventHappenedObserver:eventHappenedObservers){
        eventHappendedObserver.callback(event.number,event.toString());
    }
}

...

In the consuming class:

instanceOfClassRaisingCallback.setEventHappendedObserver(new EventHappened{
     @Override
     void callBack(int arg1, String arg2){
          doStuffWithArgs(arg1,arg2);
     }
   )};

(from memory, apologies for typos and syntax errors but you get the idea...I hope)

Good luck.



来源:https://stackoverflow.com/questions/12463610/android-custom-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!