繁体   English   中英

如何在 Android Kotlin 的主要活动之外添加或查找文本视图?

[英]How to add or find textview outside of the mainactivity in Android Kotlin?

包 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.TextView

导入 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)

    }

}

}

类 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

}

}

请尝试使用progressupdate从asynchtask到mainactivity创建回调

像:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM