[英]How to add or find textview outside of the mainactivity in Android Kotlin?
package com.example.asyntask包 com.example.asyntask
import android.content.ContentValues.TAG导入 android.content.ContentValues.TAG
import android.os.AsyncTask导入 android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity导入 androidx.appcompat.app.AppCompatActivity
import android.os.Bundle导入 android.os.Bundle
import android.util.Log导入 android.util.Log
import android.widget.Button导入 android.widget.Button
import android.widget.TextView导入 android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*导入 kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {类 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() : AsyncTask<Int, Int, Unit>() {类 CountTask() : AsyncTask<Int, Int, Unit>() {
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
}
} }
Please try to create the Callback with progressupdate from asynchtask to mainactivity请尝试使用progressupdate从asynchtask到mainactivity创建回调
like:像:
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.