Skip to content Skip to sidebar Skip to footer

How To Achieve C# Event Behavior In Java (android)

when i was programming in c# i was making very often use of events. Now I would like to achieve something similar in Java. I know both languages are diffrent and there are some dif

Solution 1:

If i understand you correctly (i'm just starting learning C#), the normal way to do it in Java is to use the observer pattern (listener pattern):

You create a listener interface with a method to be called when your event happens. That method can take some event-arguments and a sender as parameter, if you like. For example:

publicinterfaceMyListener { // This is probably your MyEventvoidmyEventFired(Object sender, MyEventArgs eventArgs);
}

publicclassMyEventArgs {
    ...something...
}

A class which is to respond to your kind of event, needs to implement the above interface. (see an example a little below (MyListeningClass))

Ok, so then you need a class (or more classes) which fires your event: MyClass. Usually MyClass has some way for other classes, who wants to respond to MyClass' event, to register themselves with MyClass. (Or more precisely, register themselves with a specific object of MyClass). This allows the MyClass-object to know which other objects it should inform about when the event happens.

This is usually done by creating a method called "add[ListenerName]" in the class firing the event - in this case "addMyListener" in MyClass. To make this example simpler, let's just assume there can only ever be one listener, so we will call it "setMyListener" instead:

publicclassMyClass {

    privateMyListener listener = null;

    // This is a method which sometimes fires an event, by calling the fireEvent() method belowpublicvoiddoSomething() {
        ...
        if (something) {
            // Let's say the event happens if "something" is true. // So now we "fire the event". What "firing the event" means, // is just to call the "myEventFired" method in the listener.fireEvent();
        }
        ...

    }

    // this is called from the method above to fire the event - i.e. to tell the listener that the event has happenedprotectedvoidfireEvent() {
        if (listener != null) {
            Object sender = this; 
            MyEventArgs eventArgs = newMyEventArgs(...something...);
            listener.myEventFired(sender, eventArgs);
        }
    }

    // This method is called by the listener, to register itself as listener on this object.// MyClass remembers the listener in the "listener" instance variable, so that // when the event happens at some later point in time, it knows which object it  // has to tell it to.publicvoidsetMyListener(MyListener listener) {
        this.listener = listener;
    }
}

(To support more than one listener, just have a list of listeners List<MyListener> listeners instead of the MyListener listener instance variable, and create an addListener and removeListener method instead of the setListener method. In the Android API they usually only allow one listener, so i thought i would show that version)

So now we just need the class which wants to listen for the event. I.e. the class implementing the MyListener interface. (This class is thus a listener). A simple example:

publicclassMyListeningClassimplementsMyListener {

    publicMyListeningClass() {
        MyClass myClass = ...get the MyClass objectfrom somewhere...;
        myClass.setMyListener(this);
    }

    // this is called by MyClass when the event occurspublicvoidmyEventFired(Object sender, MyEventArgs eventArgs) {
        System.out.println("EVENT HAPPENED!");
        System.out.println("Sender is: "+sender);
        System.out.println("MyEventArgs are: "+eventArgs);
    }    
}

(Of course you don't actually have to create the interface if you don't want to. You could of course just hardcode the MyListeningClass in MyClass instead, but it's better style to use interfaces, to decouple MyClass and MyListeningClass from each other. And it'll also be more extendable later, to allow other classes than MyListeningClass to listen for the events too.)

There are many examples of this in the Java API. For example SWING makes heavy use of listeners - for example for button-clicks, as you mention. And of course the Android API too.

I'll see if i can find some examples of this later, but it's very late and i'm very tired, so maybe tomorrow :D (and fix any spelling mistakes :D). Hope it helped a bit.

To Recap:

  • MyClass (the class producing the events) needs some way to tell other classes about that the event has happened, when the event happens. It does that by calling a method in these classes when the event happens.

  • For MyClass to be able to call a method in these other classes, they have to implement some interface.

  • The classes which want to be told when the event happens, needs a way to tell MyClass that they want to be told about it. This is the reason we need the MyClass.setMyListener method. (or if we had allowed more than one listener: the MyClass.addMyListener method)

(So there is nothing magical about this. It's just simple method calling.)


(Note that, a listener interface is usually named "[name of the event]Listener". So instead of "MyListener" i should have called it "MyEventListener", according to the naming convention, if we say that the event is called "MyEvent". But for this post i think it looked too long and less simple. UPDATE: Now that i think about it, you actually usually omit "Event" from the name, so "MyListener" is right. For example if you have an event you call "OnClickEvent", you call the interface "OnClickListener".)

Solution 2:

Your best bet would probably be to use Google Web Toolkit (GWT). You can define event handlers for GWT Widgets in much the same way as using Visual Studio/C#.

Eclipse even has a built in window builder plugin.

Post a Comment for "How To Achieve C# Event Behavior In Java (android)"