Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

android - What is the right way to communicate from a custom View to the Activity in which it resides?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

for example:

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

                }
            });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...