How to access "Activity.this" in Kotlin?

JavaAndroidKotlin

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Try this label instead

this@YourActivityName

Solution 3 - Java

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

Solution 4 - Java

Answer is: this@ActivityName

For example: You should use it if you would like to define "Context" in MainActivity.kt

var mContext:Context = this@MainActivity

Why? Because in Kotlin language @ has mean "of" such as:

val a = this@A // A's this

If you want to learn more information, you can look Kotlin Language website: This Expression in Kotlin

Solution 5 - Java

In kotlin

this@MainActivity

is equivalent to JAVA

MainActivity.this

Solution 6 - Java

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

Solution 7 - Java

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

materialDialog = MaterialDialog.Builder(this)

Solution 8 - Java

You can get the object of activity like this.

class DemoActivity : BaseActivity() {
    val builder = MaterialDialog.Builder(this@DemoActivity)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRadoView Question on Stackoverflow
Solution 1 - Javamfulton26View Answer on Stackoverflow
Solution 2 - JavaThe BalaView Answer on Stackoverflow
Solution 3 - JavaAllenView Answer on Stackoverflow
Solution 4 - JavaNamelessView Answer on Stackoverflow
Solution 5 - JavaBrian MutisoView Answer on Stackoverflow
Solution 6 - JavaShivam YadavView Answer on Stackoverflow
Solution 7 - JavaMechadroidView Answer on Stackoverflow
Solution 8 - JavaNikhil KatekhayeView Answer on Stackoverflow