我想制作一个使用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")
}
})
}
答案 0 :(得分:1)
这就是我要做的,我将创建两个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
}