首页 > 解决方案 > 如何从 kotlin 的内部类调用片段方法?

问题描述

我在片段中创建了一个方法和一个内部类。然而,在 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)
    }
}}

标签: androidandroid-studiokotlininner-classes

解决方案


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

this@BlankFragment.rotateUI

推荐阅读