我在用Kotlin编写的Activity中有一个AsyncTask作为内部类。现在,我尝试使用this@MyActivity
从AsyncTask的onPostExecute访问"活动",但AndroidStudio将其报告为"未解决的引用"错误。但这是在线建议的从InnerClass引用OuterClass的最常见方法。代码如下:
class MyActivity : AbstractAppPauseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
}
class MyTask(private var mContext: Context?, val pbMigrating: ProgressBar) :AsyncTask<Void, Int, Void>() {
private var size: Long = 0
override fun onPreExecute() {
super.onPreExecute()
...
}
override fun doInBackground(vararg params: Void?): Void? {
...
return null
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
pbMigrating.progress = values[0] as Int
}
override fun onPostExecute(result: Void?) {
super.onPostExecute(result)
this@MyActivity //<- Cannot Resolve error here
}
}
}
您必须将类作为内部
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
} inner class MyTask(private var mContext: Context?, val pbMigrating: ProgressBar) : AsyncTask<Void, Int, Void>() {
private var size: Long = 0
override fun onPreExecute() {
super.onPreExecute()
}
override fun doInBackground(vararg params: Void?): Void? {
return null
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
pbMigrating.progress = values[0] as Int
}
override fun onPostExecute(result: Void?) {
super.onPostExecute(result)
this@MyActivity //<- Cannot Resolve error here
}
}
}
MyTask类必须定义为内部类:
inner class MyTask(
private var mContext: Context?,
val pbMigrating: ProgressBar
) : AsyncTask<Void, Int, Void>()
{
...
}