Java 如何在 Kotlin 中访问“Activity.this”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41617042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:31:30  来源:igfitidea点击:

How to access "Activity.this" in Kotlin?

javaandroidkotlin

提问by Bal0r

I have this piece of Java code:

我有这段Java代码:

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

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

我想在 Kotlin 中获取 MainActivity 对象。自动转换在 处中断MainActivity.this

采纳答案by mfulton26

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

您可以MainActivity在 Kotlin 中使用限定的this. 例如:

class MyActivity : MainActivity() {
    val builder = MaterialDialog.Builder(this@MyActivity)
}

回答by The Bala

Try this label instead

试试这个标签

this@YourActivityName

回答by Allen

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

如果您从内部类调用 Activity.this,则必须将内部放在类之前

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

    inner class Inner {
        this@MyActivity // Call from the inner class 
    }
}

回答by Shivam Yadav

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

就像你在 java 中获取活动上下文作为 MainActivtiy.this 一样,在 kotlin 中你将获得作为this@MainActivity的上下文

回答by Mechadroid

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

getActivity()等效this@activity_name于 materialDialog builder 的情况

materialDialog = MaterialDialog.Builder(this)

回答by Nikhil Katekhaye

You can get the object of activity like this.

您可以像这样获取活动对象。

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

回答by canerkaseler

In Kotlin, you have to use this way:

在 Kotlin 中,你必须这样使用:

this@ActivityName

这个@ActivityName

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

例如:如果你想在 MainActivity.kt 中定义“Context”,你应该使用它

var mContext:Context = this@MainActivity

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

为什么?因为在 Kotlin 语言中 @ 的意思是“of”,例如:

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

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

如果您想了解更多信息,可以查看 Kotlin 语言网站: Kotlin 中的这个表达式

@canerkaseler

@canerkaseler