BaseFragment類匕首上超類和子類
open class BaseFragment : Fragment() {
@Inject lateinit var apiManager: ApiManager
@Inject lateinit var eventBus: EventBus
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App.getInstance().component.inject(this)
}
override fun onStop() {
eventBus.unreg(this)
super.onStop()
}
override fun onStart() {
super.onStart()
eventBus.reg(this)
}
}
RoomsFragment類
class RoomsFragment : BaseFragment() {
@Inject lateinit var roomAdapter: RoomsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App.getInstance().component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_rooms_fragment_new, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
recyclerView.adapter = roomAdapter //This line throws null or lateinit property roomAdapter has not been initialized
}
}
AdapterModule類
@Module(includes = AppModule.class)
public class AdapterModule {
@Provides //App module has EventBus so i included it in Module
RoomsAdapter provideRoomsAdapter(EventBus eventBus) {
return new RoomsAdapter(eventBus);
}
}
AppComonent類
@Singleton
@Component(modules = {AppModule.class, AdapterModule.class})
public interface ApplicationComponent {
void inject(ApiManager apiManager);
void inject(BaseFragment baseFragment);
}
注入
正如你可以看到我試圖在超類和子類中注入對象,但它不是按預期工作。 BaseFragment
注入對象工作發現但RoomsFragment
注入失敗。任何解決方案
修復: 我忘了爲ApplicationComponent中的子類RoomsFragment
添加接口。由於它的超類BaseFragment
接口存在,因此在編譯時不會引發任何錯誤。
@Singleton
@Component(modules = {AppModule.class, AdapterModule.class})
public interface ApplicationComponent {
void inject(RoomsFragment roomsFragment);
void inject(ApiManager apiManager);
void inject(BaseFragment baseFragment);
}
你在組件中定義的RoomsFragment? – Spartan
是的,我沒有..... –
我希望這不是在您的真實代碼App.getInstance()。component.inject(this)在RoomsFragment中進行評論。 – Spartan