使用LiveData/StateFlow时TextView文本重叠重复问题求助
解决TextView文本重叠问题
问题现象

点击按钮更新LiveData或StateFlow的值时,TextView未替换原有文本,而是新值与默认值重叠显示,无法正常展示最新内容。
问题原因
你的activity_main.xml中,FragmentContainerView设置了android:name属性指定了FlowsFragment,这会让Android系统自动加载该Fragment实例;同时在MainActivity.kt的onCreate方法中,又通过FragmentManager手动添加了一次FlowsFragment。同一个Fragment被加载了两次,两个实例的视图叠加在一起,导致文本重叠。
解决方案
移除FragmentContainerView中的android:name属性,保留代码中手动添加Fragment的逻辑即可。
修改后的activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.fragment.app.FragmentContainerView android:id="@+id/mainActivityFragmentContainer" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout="@layout/fragment_flows" /> </androidx.constraintlayout.widget.ConstraintLayout>
或者也可以保留android:name属性,移除MainActivity中手动添加Fragment的代码,两种方式二选一即可。
内容的提问来源于stack exchange,提问作者OTHERS
相关产品推荐
相关产品推荐

