在RecyclerView的适配器中获取上下文

3
所以,我要在RecyclerView的项目上启动一个“YouTube播放器”onClick。然而,这里有一个问题:
Intent intent = YouTubeStandalonePlayer.createVideoIntent(itemView.getContext(), DeveloperKey.DEVELOPER_KEY, "cdgQpa1pUUE");
itemView.getContext().startActivity(intent);

其中itemView是View,而在这里

createVideoIntent(itemView.getContext()

Android studio显示:

找到错误的第一个参数类型为 'Android.content.Context',需要 'android.app.Activity'

我该如何解决这个问题?我已经尝试查看类似的问题,但其中的解决方案仅限于片段和支持库,例如v4和v7。任何帮助都将不胜感激,谢谢!

3个回答

2
public class MyAdapter extends BaseAdapter {
        private Context context;

        public SampleAdapter(Context Mcontext) {
            this.context = Mcontext;
        }

        /* ... other methods ... */
    }

2

请尝试这个:

Activity activity = (Activity) itemView.getContext();
Intent intent = YouTubeStandalonePlayer
        .createVideoIntent(activity, DeveloperKey.DEVELOPER_KEY, "cdgQpa1pUUE");
itemView.getContext().startActivity(intent);

0
将您的活动传递给可回收视图。
例如像这样:
public MyAdapter(MyActivity activity){
   this.activity = activity;
}

稍后

YouTubeStandalonePlayer.createVideoIntent(this.activity, DeveloperKey.DEVELOPER_KEY, "cdgQpa1pUUE");
        itemView.getContext().startActivity(intent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接