android - 回到被破坏的活动后,RecyclerView 变空
问题描述
我有一个recyclerview ,它从Firebase 数据库中读取人员列表并将他们显示在布局上。当我第一次访问活动时,一切都按预期进行,但是当我使用BackButton完成活动并尝试再次访问该活动时,recyclerview 变为空。请注意,我尝试通过使用 SingleValueEvent 的侦听器以编程方式添加人员。
class myActivity : AppCompatActivity() {
private var index = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fisio)
Firebase.database.setPersistenceEnabled(true)
val database = Firebase.database("mydatabase")
val myRef = database.getReference("People")
val peopleList = ArrayList<MyPeopleListAdapter.MyPeopleItem>()
val code = intent.getStringExtra("key")
val recview = findViewById<RecyclerView>(R.id.recyclerViewF)
recview.layoutManager = LinearLayoutManager(this)
val adapter = MyPeopleListAdapter(peopleList)
recview.adapter = adapter
recview.setHasFixedSize(true)
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val ref = snapshot.child(code.toString()).getValue<Map<String, *>>()
val peopleListRef = snapshot.child(code.toString()).child("PeopleList")
peopleListRef.children.forEach {
val hash = it.getValue<Map<String,*>>()
val pId = it.key
val pFull = hash!!["Name"].toString()
val pEmail = hash["Email"].toString()
val pPic = hash["Pic"].toString()
val pS = hash["S"].toString()
peopleList.add(index, MyPeopleListAdapter.MyPeopleItem(
pId.toString(),
pPic,
pFull,
pEmail,
pS))
adapter.notifyItemInserted(index)
index += 1
}
}
override fun onCancelled(error: DatabaseError) {
println(error.message)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
}
解决方案
问题是回收站视图没有实现scrollToPosition()方法。所以通知适配器后,调用scroll方法,代码变为:
// ...
adapter.notifyItemInserted(index)
recview.scrollToPosition(0)
// ...
推荐阅读
- matlab - 类文件夹和命名空间中类方法的 Matlab 代码完成
- excel - 在 Excel 中使用搜索功能检索匹配条件时遇到问题
- javascript - Gremlin 暂停响应写入,因为 RequestMessage 上的 writeBufferHighWaterMark 超出
- python - 我的神经网络只返回 0、1 或其他常量值
- android - 如何使用 gradle 在 android 中执行单个 Junit 测试
- python - 如何使用新数据框映射列名并将其替换为新值
- sql - 带有 WHERE 子句的 COUNT 比没有 WHERE 子句提供更多的行
- java - 从android中的日历视图获取纪元时间
- git - Git 什么时候会成功合并 vs 冲突?
- imagemagick - 如何在imagemagick中调整图像大小但保持纵横比不变