我正在使用Kotlin在Android studio中进行测验应用。我正在从API获取数据并将其显示在活动中。现在,我正在实现一个progressBar,它指示回答每个问题有多少时间。这是我要从API获取的函数:
private fun fetch(){
val theme = intent.getIntExtra("sport", 21)
val difficulty = intent.getStringExtra("medium")
val url = "https://opentdb.com/api.php?amount=10&category=21&difficulty=medium&type=multiple"
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string()
val gson = GsonBuilder().create()
val triviaRequest = gson.fromJson(body, TriviaRequest::class.java)
val result = triviaRequest.results[0]
val question = result.question.toSpanned()
val questionCategory = result.category.toSpanned()
val correctAnswer = result.correct_answer.toSpanned()
val incorrectAnswer1 = result.incorrect_answers[0].toSpanned()
val incorrectAnswer2 = result.incorrect_answers[1].toSpanned()
val incorrectAnswer3 = result.incorrect_answers[2].toSpanned()
val questions = listOf(
correctAnswer,
incorrectAnswer1,
incorrectAnswer2,
incorrectAnswer3
)
shuffle(questions)
runOnUiThread {
val button1 = findViewById<Button>(R.id.alternative1)
val button2 = findViewById<Button>(R.id.alternative2)
val button3 = findViewById<Button>(R.id.alternative3)
val button4 = findViewById<Button>(R.id.alternative4)
questionText.text = question
themeText.text = questionCategory
button1.text = questions[0]
button1.isEnabled = true
button2.text = questions[1]
button2.isEnabled = true
button3.text = questions[2]
button3.isEnabled = true
button4.text = questions[3]
button4.isEnabled = true
button1.setOnClickListener {
button1.isClickable = false
if (button1.text == correctAnswer) {
score += 1
fetch()
} else {
button1.text = "---"
}
}
button2.setOnClickListener {
button2.isClickable = false
if (button2.text == correctAnswer) {
score += 1
fetch()
} else {
button2.text = "---"
}
}
button3.setOnClickListener {
button3.isClickable = false
if (button3.text == correctAnswer) {
score += 1
fetch()
} else {
button3.text = "---"
}
}
button4.setOnClickListener {
button4.isClickable = false
if (button4.text == correctAnswer) {
score += 1
fetch()
} else {
button4.text = "---"
}
}
}
response.close()
}
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
})
}
这就是我显示progressBar的方式:
val fetch = runCatching { fetch() }
if(fetch.isSuccess) {
val handler = Handler()
Thread(Runnable {
while (progressCount < 100) {
progressCount += 1
try {
Thread.sleep(50)
} catch (e: InterruptedException) {
e.printStackTrace()
}
handler.post {
progressBar.progress = progressCount
}
}
}).start()
}
}
现在的问题是,活动开始后,我的progressBar开始显示,但问题尚未出现。我的问题是我怎么知道我的fetch函数何时完成执行?这样我才能显示progressBar?
谢谢!
您可以研究kotlin协程并了解暂停功能,也可以使用类似这样的回调:
fun fetch (callback: ()->Unit) {
... // do the stuff
callback() // call the callback on complete
}
然后在调用fetch时,您会像这样:
fetch {
// Done fetching here, execute your code inside this
}