簡體   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