如何实现在Java C#事件的行为(Android版) [英] How to achieve c# event behavior in java (Android)

查看:254
本文介绍了如何实现在Java C#事件的行为(Android版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在C#我正在经常使用的事件进行编程。现在,我想实现在Java中类似的东西。我知道这两种语言的不同势,有在实施这样的机制有些diffrences。那么,以提供更好的画面也许我会形容一点什么,我想要得到的,因为我可能会混淆一些术语:

MyClass的包含code处理推出的 MyEvent 以及一些code,在某些情况下,启动该事件。

MyEventArgs 是一流的,从传输数据的 MyClass的并与事件发射一起被发送,因此函数处理的 MyEvent 有一些其他信息状态的 MyClass的实例。

和存在的 MyApp的类,在main方法中包含的 MyClass的并code处理实例的 MyEvent 并当事件内部引发 MyClass的某些行动在code侦听到执行 MyEvent

如果目前还不清楚,我的意思来实现酷似C#机制的背后是点击按钮,只是代替按钮有我的课,也有我的事件参数,而不是鼠标事件参数和有行为旨在通过我而不是点击。

我试过一些答案谷歌我的问题,例如我发现的网站,如:

http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html http://www.javaworld.com/javaworld /javaqa/2002-03/01-qa-0315-happyevent.html

,要么我只是失去了和/我期待在不好的地方使用错误关键字,或者是更可能的,我可以什么都不懂了这些例子/我不能改变他们的方式,我需要工作。

什么即时通讯要求,是一些例子,或code处理与使用 MyClass的, MyEvent这样的机制, MyEventArgs的ATLEAST一些草案, 的名字,指着$ C $词应该在我的课利用募集事件和一些示例使用类和Main方法事件处理的,所以它会帮助我总结我的脑海解决这个问题。

==========编辑======

也许有这样的avaliable Android开发一些事情?由于我的目标是获得进入移动应用开发后,我重温爪哇。

==========编辑======

如果有人仍然有兴趣,这里是一些示例code,它不使用我的名字文件档案化管理,只是表明在一般什么即时寻找:

难道没有办法精确解,也许有人为建议类似的事情即时寻找的东西吗?

frmTest.cs

 命名空间SampleApp
{
    公共部分类frmTest:表单
    {
        CountdownTimer ctmrTest;        公共frmTest()
        {
            的InitializeComponent();
            ctmrTest =新CountdownTimer(100);
            ctmrTest.CountdownTimerTick + =新CountdownTimer.CountdownTimerTickEventHandler(ctmrTest_CountdownTimerTick);
        }        无效ctmrTest_CountdownTimerTick(对象发件人,CountdownTimerEventArgs EA)
        {
            lblTimer.Text = ea.timeString;
            如果(ea.countdownFinished)countdownEnd();
        }        私人无效btnStart_Click(对象发件人,EventArgs的发送)
        {
            ctmrTest.Reset();
            ctmrTest.Start();
        }        无效countdownEnd()
        {
            的MessageBox.show(完成);
        }
    }
}

CountdownTimer.cs

 命名空间SampleApp
{
    公共类CountdownTimer
    {
        定时器tmrTicks =新的Timer();
        INT secondsLeft = 0;
        INT numberOfSecondsToCountdown = 0;        公共BOOL IsWorking
        {
            {返回tmrTicks.Enabled; }
        }        公共CountdownTimer(INT秒)
        {
            ...
        }        无效tmrTicks_Tick(对象发件人,EventArgs的发送)
        {
            ...
            WhenCountdownTimerTick(新CountdownTimerEventArgs(secondsLeft,numberOfSecondsToCountdown,真实));
        }        公共无效复位()
        {
            ...
            WhenCountdownTimerTick(新CountdownTimerEventArgs(secondsLeft,numberOfSecondsToCountdown,FALSE));
        }        公共无效停止()
        {
            tmrTicks.Enabled = FALSE;
        }        公共无效启动()
        {
            ,,,
        }        公共委托无效CountdownTimerTickEventHandler(对象发件人,CountdownTimerEventArgs EA);        公共事件CountdownTimerTickEventHandler CountdownTimerTick;        受保护的虚拟无效WhenCountdownTimerTick(CountdownTimerEventArgs EA)
        {
            如果(CountdownTimerTick!= NULL)
            {
                CountdownTimerTick(这一点,EA);
            }
        }
    }
}

CountdownTimerEventArgs.cs

 命名空间SampleApp
{
    公共类CountdownTimerEventArgs:EventArgs的
    {
        公共字符串TIMESTRING =;
        公共BOOL countdownFinished = FALSE;        公共CountdownTimerEventArgs(INT secondsLeft,诠释SecondsToCountdown,布尔isfinished)
        {
            countdownFinished = isfinished;
            TIMESTRING =的String.Format({} 0:00:{} 1:00,secondsLeft / 60,secondsLeft 60%);
        }
    }
}


解决方案

如果我理解正确的话(我刚开始学习C#),以正常的方式做到这一点在Java中是使用观察者模式(监听器模式)

您创建的方法的监听器接口当你的事件发生被调用。
这种方法可以采取一些事件参数和发件人为参数,如果你喜欢。
例如:

 公共接口myListener的{//这可能是你的MyEvent
    无效myEventFired(对象发件人,EventArgs的MyEventArgs);
}公共类MyEventArgs {
    ...什么...
}

一个类,这是对您的此类事件的回应,需要实现上述接口。
(看一个例子下面一点点(MyListeningClass))

好了,那么你需要一个类(或多个类),这触发您的活动: MyClass的
通常的 MyClass的有某种方式对其他类,谁愿意为 MyClass的事件作出回应,注册
自己与 MyClass的。 (或者更precisely,与特定对象登记自己的 MyClass的)。这使得在 MyClass的 -object知道哪些其他的对象应该告知当事件发生。

在类触发事件

这通常是通过创建一个名为方法完成的添加[ListenerName] - 在这种情况下, addMyListener 中的 MyClass的
为了使这个例子简单,我们只是假设有可能的永远只能有一个的监听器,所以我们将它称为 setMyListener 而不是:

 公共类MyClass的{    私人myListener的侦听器= NULL;    //这是有时会触发一个事件,通过调用下面的fireEvent()方法的方法
    公共无效DoSomething的(){
        ...
        如果(东西){
            //比方说,事件发生,如果东西是真实的。
            //所以,现在我们触发事件。什么是触发事件的意思,
            //就是打电话给听者的myEventFired的方法。
            fireEvent();
        }
        ...    }    //这是从上面的方法调用,用于触发事件 - 即告知该事件已经发生听众
    保护无效fireEvent(){
        如果(听众!= NULL){
            对象发件人=这一点;
            MyEventArgs的EventArgs =新MyEventArgs(......什么......);
            listener.myEventFired(发件人,EventArgs的);
        }
    }    //此方法由听众呼吁,要自身注册为这个对象上的监听器。
    // MyClass的记得听众中的听众的实例变量,从而使
    //当事件发生时在以后的某个点上,它知道哪些对象是
    //已经把这件事告诉。
    公共无效setMyListener(myListener的侦听器){
        this.listener =侦听器;
    }
}

(支持多个监听器,只是有位听众的名单列表< myListener的>听众而不是 myListener的侦听器实例变量,并创建一个的addListener和的removeListener方法,而不是使用setListener方法,在Android的API,他们通常只允许一个监听器,所以我想我会表明版本)

所以,现在我们只需要这要监听的事件的类。即该类实施 myListener的接口。 (这个类是这样一个监听器)。一个简单的例子:

 公共类MyListeningClass实现myListener的{    公共MyListeningClass(){
        MyClass的MyClass的= ...从某处获得MyClass的对象...;
        myClass.setMyListener(本);
    }    //这是由MyClass的事件发生时被称为
    公共无效myEventFired(对象发件人,EventArgs的MyEventArgs){
        的System.out.println(发生事件!);
        的System.out.println(发件人是:+发送者);
        的System.out.println(MyEventArgs是:+ EventArgs的);
    }
}

(当然,你实际上并不需要创建界面,如果你不想,你当然就很难code中的MyListeningClass MyClass中代替,但最好风格来使用接口,以相互分离MyClass的和MyListeningClass。此外,它还会更扩展后,允许其他类比MyListeningClass监听的事件了。)

有Java API中的许多这样的例子。例如SWING大量使用监听器 - 例如用于按钮点击,你提到。当然Android的API了。

我去看看,如果我以后能找到这样一些例子,但它已经很晚了,我很累,所以也许明天:D(并修复任何拼写错误:D)。希望它帮助了一点。

要回顾:


  • MyClass的(生产事件类)需要一些方法来告诉其他类有关该事件已经发生,当事件发生。
    它是通过调用这些类的方法,当事件发生。


  • 对于 MyClass的以能够调用的方法在这些其他类,他们要实现一些接口。


  • 当事件发生时,被告知这要的类,需要一种方法来告诉 MyClass的,他们希望
    被告知这件事。这是我们需要在 MyClass.setMyListener 方式的原因。
    (或者,如果我们已经允许多个监听器:在 MyClass.addMyListener 方式)


(所以有什么魔力这一点。这只是简单的方法调用。)

搜索结果


(需要注意的是,一个监听器接口通常命名为监听器[事件名称]。因此,而不是myListener的我应该把它叫做MyEventListener,根据命名规则,如果我们说该事件被称为MyEvent但对于这个职位,我认为它看起来太长,少简单的的更新:现在我想想,你实际上通常从名称省略事件所以myListener的是正确的。例如,如果你有你所说的OnClickEvent的事件,你调用接口OnClickListener。)

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 diffrences in implementing such mechanism. Well to give better picture maybe i will describe a little what i want to get, because i might confuse some of terminology:

MyClass contains code that handles launching MyEvent and some code that in certain situations launches that event.

MyEventArgs is class that transports data from MyClass and is sent along with event launch, so function that handles MyEvent has some additional information about state of MyClass instance.

And there is MyApp class that in main method contains instance of MyClass and code handling MyEvent and when event is raised inside MyClass certain actions are performed in code that listens to MyEvent.

If it's still unclear, what i mean to achieve is exactly like c# mechanism that is behind button click, just instead of button there is my class, there are my event arguments instead of mouse event args and there is behaviour designed by me instead of click.

I've tried to google some answers to my problem and for example i found sites like:

http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html

And either im just lost and I'm looking in bad places/using bad keywords, or what more possible i can't understand anything out of these examples/i can't transform them to work in way I need.

What im asking for, is some example, or atleast some draft of code handling such mechanism with use of MyClass, MyEvent, MyEventArgs, names, pointing code i should use in my class to raise event and some sample use of class and handling of event in Main method, so it would help me wrap my mind around this problem.

==========Edit========

Maybe there are some things like that avaliable for android developers? As my goal is to get to get into mobile apps development after i dust off java.

==========Edit========

If anyone still interested, here is some sample code, it doesn't use names i metioned, just shows in general what im looking for:

And is there no exact solution, maybe somone would suggest something similar to thing im looking for?

frmTest.cs

namespace SampleApp
{
    public partial class frmTest : Form
    {
        CountdownTimer ctmrTest;

        public frmTest()
        {
            InitializeComponent();
            ctmrTest = new CountdownTimer(100);
            ctmrTest.CountdownTimerTick += new CountdownTimer.CountdownTimerTickEventHandler(ctmrTest_CountdownTimerTick); 
        }

        void ctmrTest_CountdownTimerTick(object sender, CountdownTimerEventArgs ea)
        {
            lblTimer.Text = ea.timeString;
            if (ea.countdownFinished) countdownEnd();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ctmrTest.Reset();
            ctmrTest.Start();
        }

        void countdownEnd()
        {
            MessageBox.Show("Finish");
        }
    }
}

CountdownTimer.cs

namespace SampleApp
{
    public class CountdownTimer
    {
        Timer tmrTicks = new Timer();
        int secondsLeft = 0;
        int numberOfSecondsToCountdown = 0;

        public bool IsWorking
        {
            get { return tmrTicks.Enabled; }
        }

        public CountdownTimer(int seconds)
        {
            ...
        }

        void tmrTicks_Tick(object sender, EventArgs e)
        {
            ...
            WhenCountdownTimerTick(new CountdownTimerEventArgs(secondsLeft, numberOfSecondsToCountdown, true));
        }

        public void Reset()
        {
            ...
            WhenCountdownTimerTick(new CountdownTimerEventArgs(secondsLeft, numberOfSecondsToCountdown, false));
        }

        public void Stop()
        {
            tmrTicks.Enabled = false;
        }

        public void Start()
        {
            ,,,
        }

        public delegate void CountdownTimerTickEventHandler(object sender, CountdownTimerEventArgs ea);

        public event CountdownTimerTickEventHandler CountdownTimerTick;

        protected virtual void WhenCountdownTimerTick(CountdownTimerEventArgs ea)
        {
            if (CountdownTimerTick != null)
            {
                CountdownTimerTick(this, ea);
            }
        }
    }
}

CountdownTimerEventArgs.cs

namespace SampleApp
{
    public class CountdownTimerEventArgs : EventArgs
    {
        public string timeString = "";
        public bool countdownFinished = false;

        public CountdownTimerEventArgs(int secondsLeft, int SecondsToCountdown, bool isfinished)
        {
            countdownFinished = isfinished;
            timeString = string.Format("{0:00}:{1:00}", secondsLeft / 60, secondsLeft % 60);
        }
    }
}

解决方案

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:

public interface MyListener { // This is probably your MyEvent
    void myEventFired(Object sender, MyEventArgs eventArgs);
}

public class MyEventArgs {
    ...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:

public class MyClass {

    private MyListener listener = null;

    // This is a method which sometimes fires an event, by calling the fireEvent() method below
    public void doSomething() {
        ...
        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 happened
    protected void fireEvent() {
        if (listener != null) {
            Object sender = this; 
            MyEventArgs eventArgs = new MyEventArgs(...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.
    public void setMyListener(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:

public class MyListeningClass implements MyListener {

    public MyListeningClass() {
        MyClass myClass = ...get the MyClass object from somewhere...;
        myClass.setMyListener(this);
    }

    // this is called by MyClass when the event occurs
    public void myEventFired(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".)

这篇关于如何实现在Java C#事件的行为(Android版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆