How to access “Activity.this” in Kotlin?

2020-02-02 10:02发布

I have this piece of Java code:

MaterialDialog builder = new MaterialDialog.Builder(MainActivity.this)

I want to get the MainActivity object in Kotlin. The automatic conversion breaks at MainActivity.this.

6条回答
我只想做你的唯一
2楼-- · 2020-02-02 10:22

Just as you do in java for getting the context of activity as MainActivtiy.this , in kotlin you will get the context as this@MainActivity

查看更多
Rolldiameter
3楼-- · 2020-02-02 10:28

Try this instead

this@ActivityName
查看更多
家丑人穷心不美
4楼-- · 2020-02-02 10:30

If you are calling Activity.this from an inner class, you have to put inner before the class

class MyActivity : MainActivity() {
    // Call from class itself
    val builder = MaterialDialog.Builder(this@MyActivity) 

    inner class Inner {
        this@MyActivity // Call from the inner class 
    }
}
查看更多
做个烂人
5楼-- · 2020-02-02 10:31

getActivity() equivalent is this@activity_name in case of builder for materialDialog

materialDialog = MaterialDialog.Builder(this)
查看更多
The star\"
6楼-- · 2020-02-02 10:32

You can get a reference to your MainActivity object in Kotlin by using a qualified this. e.g.:

class MyActivity : MainActivity() {
    val builder = MaterialDialog.Builder(this@MyActivity)
}
查看更多
Explosion°爆炸
7楼-- · 2020-02-02 10:37

You can get the object of activity like this.

class DemoActivity : MainActivity() {
    val builder = MaterialDialog.Builder(this@DemoActivity)
}
查看更多
登录 后发表回答