Home » Android » java – How to access "Activity.this" in Kotlin?

java – How to access "Activity.this" in Kotlin?

Posted by: admin March 11, 2020 Leave a comment

Questions:

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.

How to&Answers:

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([email protected])
}

Answer:

Try this instead

[email protected]

Answer:

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([email protected]) 

    inner class Inner {
        [email protected] // Call from the inner class 
    }
}

Answer:

Just as you do in java for getting the context of activity as MainActivtiy.this , in kotlin you will get the context as [email protected]

Answer:

getActivity() equivalent is [email protected]_name
in case of builder for materialDialog

materialDialog = MaterialDialog.Builder(this)

Answer:

You can get the object of activity like this.

class DemoActivity : MainActivity() {
    val builder = MaterialDialog.Builder([email protected])
}

Answer:

In Kotlin, you have to use this way:

[email protected]

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

var mContext:Context = [email protected]

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

val a = [email protected] // A's this

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

@canerkaseler