我们可以从适配器调用startActivityForResult吗?如何获得响应? [英] can we call startActivityForResult from adapter?How to get the response?
问题描述
是否可能在适配器中包含方法startActivtyForResult
?然后如何获取响应?在哪里执行回叫功能?
is it possible to have method startActivtyForResult
within an adapter?Then how to get the response? Where to execute the call back function?
推荐答案
是的,有可能.您需要适配器中Context
的引用并调用该活动:
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.
您可以像往常一样使用onActivityResult
在封闭活动中获得结果.
You get the result in the enclosing activity using onActivityResult
as usual.
例如,
在适配器中:
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");
}
在第二项活动中,与往常一样使用setResult
和finish
.
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);
}
这篇关于我们可以从适配器调用startActivityForResult吗?如何获得响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!