什么是正确的方式从自定义视图在它所在的活动进行沟通?自定义、视图、所在、正确

2023-09-04 07:11:40 作者:酒话醉心i

我有一个延伸微调自定义视图类。我试图弄清楚什么倾诉,它的嵌入,当用户进行选择的活动的正确方法。我看到 OnItemSelected 听者获得一个参考适配器,但我不清楚我是否应该使用该适配器和行走了其父链弄好了,或者我应该直接对话的上下文(出于某种原因,不安全感,即使我想不出在它可能会失败,随便的方式)。

I have a custom View class that extends Spinner. I'm trying to figure out what the correct way to talk to the Activity that it's embedded in is, when the user makes a selection. I see that the OnItemSelected listener gets a reference to the Adapter, but I'm not clear on whether or not I should be using this adapter and walking up its parent chain somehow, or if I should just talk directly to the context (for some reason that doesn't feel safe, even though I can't think of a way in which it might fail, offhand).

推荐答案

正确的方式来做到这一点,是通过暴露,你的看法拿着引用他的实例的接口来听到自定义视图,你举办​​的活动应该实现。酷似OnItemSelected接口,并且Android的意见自曝正在实施的任何事件。这是观察者设计模式。

the right way to do that, is to "listen" to your custom view by exposing an interface which your view holding a reference to instance of him, and you hosting activity should implement. exactly like the OnItemSelected interface and any events which android views are exposing is been implemented. this is the observer design pattern.

例如:

public class MyCustomSpinner extends Spinner {
public MyCustomSpinner(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public interface IMyEventListener {
    public void onEventAccured();
}

private IMyEventListener mEventListener;

public void setEventListener(IMyEventListener mEventListener) {
    this.mEventListener = mEventListener;
}

protected void someMethodWhichDoingSomthingAndShouldRaiseAlsoTheEvent() {

    /*
     * Some Code which the function doing //more code...
     */

    if (mEventListener != null) {
        mEventListener.onEventAccured();
    }
}
}

这是你将如何使用它从你的活动:

this is how you will use it from your activity:

            mMyCustomSpinner.setEventListener(new IMyEventListener() {

                @Override
                public void onEventAccured() {
                    // TODO Auto-generated method stub

                }
            });