在onAttach()之后片段丢失上下文

时间:2019-11-22 19:03:36

标签: fragment androidx

我有一个插入了主持人的片段。启动片段之后,在我的attach()函数上我有了上下文,但是在那之后,在onViewCreated中,我调用了演示者,这个调用了我的片段以显示Toast(通过接口),但是此时上下文为null,活动为空值。我试图创建一个变量来持久保留附加上下文,但是在onViewCreated也为null之后。

class NotificationsFragment : Fragment(),HasSupportFragmentInjector, RewardsView {

@Inject
lateinit var presenter: RewardsPresenter

@Inject
lateinit var mDispatchingAndroidInjector : DispatchingAndroidInjector<Fragment>

private lateinit var currentContext: Context

private lateinit var notificationsViewModel: NotificationsViewModel

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    notificationsViewModel =
        ViewModelProviders.of(this).get(NotificationsViewModel::class.java)
    val root = inflater.inflate(R.layout.fragment_notifications, container, false)
    val textView: TextView = root.findViewById(R.id.text_notifications)
    notificationsViewModel.text.observe(this, Observer {
        textView.text = it
    })
    return root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    presenter.onViewCreated()
}

override fun onAttach(context: Context) {
    AndroidSupportInjection.inject(this)
    super.onAttach(context)
    currentContext = context
}

override fun supportFragmentInjector(): AndroidInjector<Fragment> {
    return mDispatchingAndroidInjector
}

override fun toast() {
    Toast.makeText(currentContext, "Test", Toast.LENGTH_SHORT).show()
}

0 个答案:

没有答案