android - RecyclerView 交换两个适配器
问题描述
我想制作一个使用 API 显示最后 15 场比赛和接下来 15 场比赛的应用程序。我创建了一个具有 2 个不同列表视图的 RecyclerView。一个用于最后一场比赛,另一个用于下一场比赛。我还创建了 2 个不同的适配器,所以当我单击不同的导航栏时,它会将视图(例如最后一个匹配)更改为另一个视图(下一个匹配)。但是,当我单击第二个按钮(下一个匹配项)时,它强制停止。
我认为问题出在适配器集中,但我不知道在哪里
这是我的代码:
MainActivity.kt
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
//Prev Match
recyclerView_main.layoutManager = LinearLayoutManager(this)
fetchJsons()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
//Next Match
recyclerView_main.layoutManager = LinearLayoutManager(this)
fetchJson()
return@OnNavigationItemSelectedListener true
}
}
false
}
fun fetchJsons(){
//Json for prev match
val url = "https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback{
override fun onResponse(call: Call?, response: Response?){
println("sukses")
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val prevMatch = gson.fromJson(body, PrevMatch::class.java)
runOnUiThread { recyclerView_main.adapter = MainAdapters(prevMatch) }
}
override fun onFailure(call: Call?, e: IOException?){
println("failed request")
}
})
}
// Next Match JSON
fun fetchJson(){
val url = "https://www.thesportsdb.com/api/v1/json/1/eventsnextleague.php?id=4328"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback{
override fun onResponse(call: Call?, response: Response?){
println("sukses")
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val nextMatch = gson.fromJson(body, NextMatch::class.java)
runOnUiThread { recyclerView_main.adapter = MainAdapter(nextMatch) }
}
override fun onFailure(call: Call?, e: IOException?){
println("failed request")
}
})
}
解决方案
这就是我要做的,我将创建两个 recyclerView 并在它们之间切换。并在它们之间划分来自 API 的数据。
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
//Prev Match
recyclerView_Next_Match.visibility = View.GONE
recyclerView_Prev_Match.visibility = View.VISIBLE
fetchJsons()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
//Next Match
recyclerView_Prev_Match.visibility = View.GONE
recyclerView_Next_Match.visibility = View.VISIBLE
fetchJson()
return@OnNavigationItemSelectedListener true
}
}
false
}
推荐阅读
- python - 需要 SQL 查询帮助(使用flask-sqlalchemy)列出所有未在复合多对多表中列出的项目
- python - 如何从多个文件制作子图?Python matplot 库
- angular - 如何在 Angular 的 MatTableModule 中为每一列添加过滤器?
- php - 读取发送到 Laravel 路由的 CSV 文件
- opengl - 有什么方法可以在 hlsl/glsl 片段着色器中按原语获得片段(像素)的百分比覆盖率?
- c - C中的指针和内存算法
- ruby-on-rails - 我怎样才能删除rails对象,每个都做信息
- rust - Rust 中的一个可变引用真的被强制执行了吗?
- angular - 如何让 rxjs 暂停流,然后稍后重新开始
- javascript - 错误消息未呈现 | 网址验证