引用内部类的活动时Kotlin错误

时间:2017-08-28 10:44:00

标签: android android-asynctask kotlin

我有一个AsyncTask作为我在Kotlin中编写的Activity中的内部类。现在,我尝试使用this@MyActivity从我的AsyncTask的onPostExecute访问Activity,但Android Studio将其报告为Unresolved Reference错误。但这是在线建议从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 
    }


}

}

2 个答案:

答案 0 :(得分:4)

你必须将类作为内部

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
        }
    }
}

答案 1 :(得分:1)

MyTask类必须定义为内部类:

inner class MyTask(
    private var mContext: Context?,
    val pbMigrating: ProgressBar
) : AsyncTask<Void, Int, Void>()
{
    ...
}