Android:如何制作我自己的EventListener?

时间:2012-07-03 03:17:34

标签: android event-listener

今天我被告知我们可以在我们的Android项目中引入MVC(或准MVC)架构。我有一些类来包含主要由用户输入的信息,我希望我的视图(假设它是TextView,为了讨论起见)来显示它。我最初的想法是,每当我更新包含数据的类时,我都会调用一种方法在我的TextView上反映它。

Data d = new Data();
TextView t = (TextView) findViewById(R.id.IamTextView);

// ....

d.setS("Foo");           //  <--- Data updated!
t.setText(d.getS());   //  <--- View updated, too!

这无疑是蹩脚的,尽管只要数据更新的情况非常有限并且我们知道它们的位置非常有限,但我想尝试更酷更聪明的东西。所以我正在定义一个自定义EventListener ...

public class Data {
    protected int i;
    protected double d;
    protected String s; 
    //Setter & Getter omitted!
}

public interface Data.onUpdatedListener {
    public void onUpdated (Data d);
}

public class TestActivitiy extends Activity implements Data.onUpdatedListener {

        Date[] d;

        //onCreate() omitted!

        @Override public void onUpdated (Data d) {
            // I want to reflect this change on my Views, like below.
            TextView t = (TextView) findViewById(R.id.IamTextView);
            t.setText(d.getS());
        }
}

我知道我必须创建一个用作Controller的专用类,其作用是通知Activity更新发生的事件以及它是哪个对象(如果我在{{中创建每个成员变量,它可能会非常有用) 1}}作为Data的参数,这样我只能向Activity发送“差异”,而不是整个对象。

我的问题01: 我不太确定知道如何通知我的更新活动(换句话说,如何触发onUpdated()方法)。

我的问题02: 我不太确定如何确定对象的更新。如果任何成员不同,我想通知它,但如何?我们应该始终保留对象的最新状态,并将所有成员变量与当前变量的变量进行比较吗?

1 个答案:

答案 0 :(得分:3)

在您要更新Data的类中,定义侦听器并为侦听器提供setter方法。

class Data {
    A a;
    B b;
    C c;

    //...constructor, setter, getter, etc
}

class A {
    Listener listener;

    interface Listener {
        void onUpdate(Data data);
        // another abstract method accepting A, B and C as parameters,
        // just an example and can be omitted if onUpdate(Data) is sufficient
        void onUpdate(A a, B b, C c);
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public void update(Data data) { // the method that is to update the Data
        if (listener != null) {
            listener.onUpdate(data);
            listener.onUpdate(data.a, data.b, data.c);
        }
    }

    public void update(A a, B b, C c) { // another method to update the Data
        if (listener != null) {
            // Assume you have this constructor for Data,
            // just for the ease of understanding.
            listener.onUpdate(new Data(a, b, c));
            listener.onUpdate(a, b, c);
        }
    }
}

class B implements A.listener {
    // In somewhere
    setListner(this);

    @Override
    void onUpdate(Data data) {
       // your implementation
    }

    @Override
    void onUpdate(A a, B b, C c) {
       // your implementation
    }
}

<强> EDITED 在侦听器中添加了另一个回调方法,用于演示侦听器的用法。