引用内部类中的"活动"时出现Kotlin错误



我在用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>()
{
...
}

相关内容

  • 没有找到相关文章

最新更新