0

I'm mostly C# developer and I'm recently working on some Android project. I have to implement some custom written events in Android, but I'm not sure how to do that. I wrote a C# code for what I want to do, so if anyone can help me with translating it into Android code, that would be appreciated.

I need to have a custom function (event), placed at MySecondClass, which can be triggered from MyFirstClass. For example, we have the class:

private class MyFirstClass
{
    private event EventHandler<MyCustomEventArgs> _myCustomEvent;
    public event EventHandler<MyCustomEventArgs> MyCustomEvent
    {
        add { _myCustomEvent += value; }
        remove { _myCustomEvent -= value; }
    }

    public void Initialize()
    {
        MySecondClass myObjectSecondClass = new MySecondClass();
        this.MyCustomEvent += myObjectSecondClass.SomeMethodSecondClass;
    }

    public void SomeMethodFirstClass(int index)
    {
        //here we will trigger the event with some custom values
        EventsHelper.Fire(this.MyCustomEvent, this, new MyCustomEventArgs(index));
    }
}

The MyCustomEventArgs is defined as:

public class MyCustomEventArgs : EventArgs
{
    public int index;

    public MyCustomEventArgs(int indexVal)
    {
        index = indexVal;
    }
}

And the the second class is defined as:

private class MySecondClass
{
    public void SomeMethodSecondClass(object sender, MyCustomEventArgs e)
    {
        //body of the method
        //we can use e.index here in the calculations
    }
}

So I'm not sure how to handle with these "Event" related commends in Android.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
delux
  • 1,694
  • 10
  • 33
  • 64

1 Answers1

0

Its all interfaces in java. No fancy complicated key word here :)

There should be an interface which the second class implements.

public interface EventHandler{
     void onEventFired(EventParams e);
}

public class MyFirstClass{
     EventHandler eventHandler;

     public void initialize(){
         eventHandler = new MySecondClass();
     }

     public void method(){
         EventParams eventParams = new EventParams();
         //fire event here
         eventHandler.onEventFired(eventParams);
     }
}

public class MySecondClass implements EventHandler{
    @Overrride
    void onEventFired(EventParams e){
        //handle event here
    }
}

I hope you get the idea

saiedmomen
  • 1,401
  • 16
  • 33