【发布时间】:2019-05-04 08:53:15
【问题描述】:
我正在使用 MVP 架构开发应用程序。其中一个部分只有 3 个带有一些文本视图和编辑文本的片段。但是,有时我会在第二个片段中获得空视图(尤其是 textview)。我把初始化代码放在onViewCreated/onActivityCreated,但还是不行。
这是我的xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:background="@color/colorBackground">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/ll_header"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center"
android:background="@color/colorPrimaryLight"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tv_initialName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/profile_title_margin"
android:layout_marginBottom="@dimen/profile_title_margin"
android:textColor="@android:color/white"
android:textSize="@dimen/profile_title_textSize"
android:paddingTop="@dimen/profile_title_padding_topBottom"
android:paddingBottom="@dimen/profile_title_padding_topBottom"
android:paddingRight="@dimen/profile_title_padding_leftRight"
android:paddingLeft="@dimen/profile_title_padding_leftRight"
android:background="@drawable/bg_profiletitlename"
/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
app:layout_constraintTop_toBottomOf="@id/ll_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
我的片段(顺便说一句,我使用 Koin 注入):
private val presenter:ProfilePresenter by inject{ parametersOf(this) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_profile,container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
presenter.initNames()
}
override fun setUserInitialChar(initialChar: Char) {
tv_initialName.text = initialChar.toString()
}
我的主持人:
override fun initNames() {
view.setUserInitialChar(AppPreferences.customer.username.capitalize().first())
}
我的 tv_initialName 为 null 时出现错误,但如果应用程序是第一次启动并显示该片段,则可以显示视图。只有当我尝试使用“FragmentTransaction.replace”导航回片段时才会出现问题。
我认为 onViewCreated 中的视图不能为空。我在这里做错了什么?
【问题讨论】:
-
嗨,几周前我遇到了同样的问题,我记得我成功地解决了它,但不记得如何解决,如果你明天仍然需要帮助,我可以查看我的代码并帮助你。
-
请。对所有这些片段的生命周期感到非常沮丧
标签: android android-fragments android-view fragment-lifecycle