Android 我们可以从适配器调用 startActivityForResult 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11882927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can we call startActivityForResult from adapter?
提问by napster
is it possible to have method onActivityResume
within adapter
& call startActivityForResult
?
是否可以onActivityResume
在adapter
& call 中使用方法startActivityForResult
?
回答by user936414
Yes. Just pass the context of the activity to the adapter in the adapter's constructor (here stored as mContext). In getView, just call
是的。只需将活动的上下文传递给适配器构造函数中的适配器(此处存储为 mContext)。在 getView 中,只需调用
((Activity) mContext).startActivityForResult(intent,REQUEST_FOR_ACTIVITY_CODE);
回答by eugeneek
Not necessarily pass to pass context in adapter's constructor. You can get context from parent ViewGroup. Sample for RecyclerView adapter:
不一定要在适配器的构造函数中传递上下文。您可以从父 ViewGroup 获取上下文。RecyclerView 适配器示例:
Context mContext;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
...
}
Sample for ListView BaseAdapter
ListView BaseAdapter 示例
Context mContext;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
mContext = parent.getContext();
...
}
And use it wherever you want
并随心所欲地使用它
((Activity) mContext).startActivityForResult(intent, REQUEST_FOR_ACTIVITY_CODE);
回答by Ali Nawaz
Offcource...
场外...
((Activity) context).startActivityForResult(intent, 911);
Caution !!
注意!!
Only pass MyActivity.thisfrom activity to adapter as context.
仅将MyActivity.this从活动传递到适配器作为上下文。
Only pass getActivity(); from fragment to adapter as context.
只通过getActivity();从片段到适配器作为上下文。