在FragmentA()中,我从先前的Fragment获取数据
class FragmentA():Fragment() {
private lateinit var personList: MutableList<Person>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
personList = it.getParcelableArrayList<Person>("person") as MutableList<Person>
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(personList.isEmpty()){
showEmptyContainer()
}else{
recyclerAdapter.setItems(personList)
}
}
现在,当我打开FragmentA()时,此代码有效,但是现在,如果我从此片段转到FragmentB()并返回,则数据将重复。因此,我尝试清洁阵列并再次设置
class FragmentA():Fragment() {
private lateinit var personList: MutableList<Person>
private var backupList:MutableList<Person> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
personList = it.getParcelableArrayList<Person>("person") as MutableList<Person>
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(personList.isEmpty()){
showEmptyContainer()
}else{
backupList.clear()
backupList = personList
recyclerAdapter.setItems(backupList)
}
}
这样做,回来时可以使用,但是由于某种原因,当我两次执行此操作时,它会显示一个空容器,所以我的问题是
如何在前进导航并按后退按钮的同时保留此片段personList?
谢谢
答案 0 :(得分:1)
您可以使用onSaveInstance
,然后如果您的onCreate
不为空,请签入savedInstanceState
,这是一个可以帮助您进行设置的主题。
onSaveInstanceState () and onRestoreInstanceState ()