SingleWave Games
SingleWave Games

Reputation: 2648

Android Custom Event

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

Upvotes: 1

Views: 4737

Answers (1)

Simon
Simon

Reputation: 14472

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.

Upvotes: 2

Related Questions