从自定义视图与其所在的活动进行通信的正确方法是什么? [英] What is the right way to communicate from a custom View to the Activity in which it resides?

查看:31
本文介绍了从自定义视图与其所在的活动进行通信的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展 Spinner 的自定义 View 类.我试图弄清楚当用户做出选择时,与它嵌入的 Activity 对话的正确方法是什么.我看到 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 onEventOccurred();
    }

    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.onEventOccurred();
        }
    }
}

这是您将如何在您的活动中使用它:

this is how you will use it from your activity:

            mMyCustomSpinner.setEventListener(new IMyEventListener() {

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

                }
            });

这篇关于从自定义视图与其所在的活动进行通信的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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