gpt4 book ai didi

android - 为什么在Kotlin的Fragment中将 “activity”链接到 “getActivity()”?

转载 作者:行者123 更新时间:2023-12-02 12:41:11 25 4
gpt4 key购买 nike

我正在阅读向日葵代码,该代码将显示如何在Android开发中使用Kotlin:https://github.com/android/sunflower/blob/master/app/src/main/java/com/google/samples/apps/sunflower/HomeViewPagerFragment.kt

在第50行:

(activity as AppCompatActivity).setSupportActionBar(binding.toolbar)

但找不到“ Activity ”的定义位置。如果在Android Studio中使用“ctrl + click”,它将跳转到Fragment.java中的“getActivity()”。如果有人可以告诉我定义的位置以及它的神奇之处,它会跳到“getActivity()”吗?

它似乎是AppCompatActivity或Fragment或任何父类(super class)中的var,但我不知道如何定位它。

最佳答案

这是Kotlin,不是Android SDK。

引用the Kotlin documentation:

Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin.



在这种情况下,我们只有 getActivity(),没有 setActivity(),因此Kotlin在语法上将其视为 val

关于android - 为什么在Kotlin的Fragment中将 “activity”链接到 “getActivity()”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59553100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com