Android的公共接口

Android的公共接口,android,interface,Android,Interface,我的界面需要一些帮助。我想我一点也不理解他们。 因此,我创建了这个接口,以便在某个事件发生时通知实现它的每个类 public interface OnColorsChangeListener { void onColorsChangeListener(ColorsProp colorsProp); } 持有接口的我的类: private OnColorsChangeListener mCallback; ... // other code // the event

我的界面需要一些帮助。我想我一点也不理解他们。 因此,我创建了这个接口,以便在某个事件发生时通知实现它的每个类

public interface OnColorsChangeListener {
    void onColorsChangeListener(ColorsProp colorsProp);
}

持有接口的我的类:

   private OnColorsChangeListener mCallback;

... // other code

    // the event occurs here so i call:
    mCallback.onColorsChangeListener(mProps);
    // but of course here i get an NPE becouse this is undefined in this class.. well,     with some replies here i'll understand better how to use that for reach my point

实现它的类:

public class ClassTest implements OnColorsChangeListener {

... // other code

@Override
public void onColorsChangeListener(ColorsProp colorsProp) {
    Log.d(TAG, "Color changed! " + colorsProp.color);
}

我把它分为4/5类,以便在同一时间收到颜色变化的通知。我很确定原因是我不太了解它们是如何工作的,所以有人能给我指出正确的方向吗?谢谢大家!

接口只是将一组相关方法组合在一起的一种方式。然后,实现此接口需要实现由接口分组在一起的所有方法

Java教程对该主题有很好的理解:

下面是一个关于android中侦听器接口的Stackoverflow线程:


简而言之,您不直接使用接口,因为它只指定应该实现哪些实现类的方法。

示例说明:

您必须实例化回调&它必须是类的实例

private OnColorsChangeListener mCallback;

mCallback = new ClassTest();


mCallback.onColorsChangeListener(mProps);
但是,如果需要多个回调,则需要使用Observer模式。 简单的例子:

private List<OnColorsChangeListener> mCallbacks = new ArrayList<OnColorsChangeListener>();

mCallbacks.add(new ClassTest());
mCallbacks.add(new OtherClass());

for(OnColorsChangeListener listener : mCallbacks) {
   listener.onColorsChangeListener(mProps);
}


持有接口的类应该实现什么功能?您可能需要阅读。应该通知其他人的类是具有私有OnColorsChangeListener mCallback的类;在我看来,你想使用一个广播接收器,然后在所有你想同时接收此事件的地方注册这些接收器。好吧,好吧。。。我想我现在站不住了!所以我面临着一个错误的方法来获得我的分数。也许你可以给我指出一个方法,在事件发生时通知一些类?(不使用广播)@iGio90-Blundell给出了一个很好的例子,说明了如何在您的案例中做到这一点,我相信您已经注意到了:感谢您的解释!旁注:回调函数和侦听器的含义略有不同(也包括观察者)。尽量不要像上面那样把它们混在一起。回调是指当一件事情完成时&你在最后得到一个回调。监听器通常可以在事件之后或事件之间调用&多次etcgreat,因此我确实需要一个监听器:D
mCallbacks.add(mClassTest);