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
341 views
in Technique[技术] by (71.8m points)

android - can we call startActivityForResult from adapter?How to get the response?

is it possible to have method startActivtyForResult within an adapter?Then how to get the response? Where to execute the call back function?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, it's possible. You need a reference for the Context in the adapter and call the activity:

Intent intent = new Intent(context, TargetActivity.class);
((Activity) context).startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);

Beware that context must be an activity context or this code will fail.

You get the result in the enclosing activity using onActivityResult as usual.

So, for example:

In your adapter:

MyAdapter(Context context) {
    mContext = context;
}

public View getView(int position, View convertView, ViewGroup parent) {
    …
    open.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            …
            Activity origin = (Activity)mContext;
            origin.startActivityForResult(new Intent(mContext, SecondActivity.class), requestCode);
        }   
    });
    …
}

public  void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("MyAdapter", "onActivityResult");
}

In your second activity, do as usual with setResult and finish.

In your main activity, capture the result and pass to the adapter callback:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mAdapter.onActivityResult(requestCode, resultCode, data);
}

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

...