【问题标题】:How to call a fragment method from an inner class in kotlin?如何从 kotlin 的内部类调用片段方法?
【发布时间】:2020-06-04 00:09:33
【问题描述】:

我在片段中创建了一个方法和一个内部类。然而,在 Fragment 的内部类中无法访问外部类方法?如何在片段的内部类中调用外部类方法或成员。以下是我的代码:

class BlankFragment : Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    mOrientationListener = OrientationChangeListener(requireContext())

}

fun rotateUI(orientation: Int){
    /// something
}

/**
 * This callback returns rotation angle of the phone, to make it return orientation angles enable it on onStart and disable it onPause
 */
private var mOrientationListener: OrientationChangeListener? = null

internal class OrientationChangeListener (context: Context?) : OrientationEventListener(context) {
    /**      portrait
     * (0, 359)
     *
     * (270)            (90)
     * (land)           (land)
     */
    override fun onOrientationChanged(orientation: Int) {

            // this method is inaccessible
            //rotateUI(orientation)
    }
}}

【问题讨论】:

    标签: android android-studio kotlin inner-classes


    【解决方案1】:

    对于内部类,关键字应该是内部而不是内部,然后您可以使用它来访问方法,例如:-

    this@BlankFragment.rotateUI
    

    【讨论】:

    • Sandeep Kumar 感谢您的回答。我已将其更改为内部,它起作用了。不使用内部类的 this@BlankFragment 指示符仍然可以访问 rotateUI。
    • this@BlankFragment 仅在 OrientationChangeListener 本身有 rotateUI 成员遮蔽 BlankFragment 时才需要。
    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多