包com.example.asyntask
导入android.content.ContentValues.TAG
导入android.os.AsyncTask
导入androidx.appcompat.app.AppCompatActivity
导入android.os.Bundle
导入android.util.Log
导入android.widget.Button
导入android.widget.Text查看
导入kotlinx.android.synthetic.main.activity_main.*
类MainActivity:AppCompatActivity(({
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnStart.setOnClickListener {
val tvCounter=findViewById<TextView>(R.id.tvCounter)
CountTask().execute(5)
}
}
}
class CountTask((:异步任务<Int,Int,单位>(({
private val tag: String? = "Async"
override fun doInBackground(vararg params: Int?) {
Log.d(tag, "doInBackground: started")
val n: Int = params[0]!!
for (i in 0 until n) {
wait1Sec()
publishProgress(i)
}
}
private fun wait1Sec():Unit{
val start =System.currentTimeMillis()
while(System.currentTimeMillis()<start+1000){}
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
//WANT TO WRITE TEXT IN TEXT VIEW BUT HOW TO GET VIEW HERE
}
}
请尝试创建从异步任务到主活动的进度更新回调
类似:
Interface UpdateListener{
fun onProgressUpdate(progress:Int);
}
class CountTask(val listener:UpdateListener) : AsyncTask<Int, Int, Unit>() {
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
//WANT TO WRITE TEXT IN TEXT VIEW BUT HOW TO GET VIEW HERE
listener.onpreogressupdate(...)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnStart.setOnClickListener {
val tvCounter=findViewById<TextView>(R.id.tvCounter)
CountTask(object:listener:UpdateListener{
override fun onProgressUpdate(progress:Int){
//TODO update here
}
}).execute(5)
}
}