我有一个场景,我应该在我的recyclerview中注入一个Class。为了注入我的匕首类,我需要掌握上下文。所以我在recyclerview类中编写了以下代码
Components.<DepComponent>getFrom(parent.getContext()).inject(this);
在theDepComponent
里面,我有一个注入方法,其中还添加了这个特定的回收站视图
当我运行代码时,我收到此错误
android.view.ContextThemeWrapper cannot be cast to target.dagger.HasComponent
我试图施放(Activity)parent.getContext()
但是引发了以下错误
android.view.ContextThemeWrapper cannot be cast to Activity
有关如何解决此问题的任何建议?看起来像parent.getContext()正在返回没有被转换为活动的ContextThemeWrapper
如果它是非基于活动的上下文,则可以使用以下方法从上下文或throw和exception获取活动:
private fun getActivity(context: Context): Activity {
return when (context) {
is Activity -> context
is ContextWrapper -> getActivity(context.getBaseContext())
else -> error("Non Activity based context")
}
}
像这样:
Components.<DepComponent>getFrom(getActivity(context)).inject(this);