首页 > 解决方案 > 如何使用 Kotlin 在内部创建接口方法?

问题描述

我写了一个简单的 SwipeLayout 库。我的目标是通过 GitHub 将它发布给包括我自己在内的所有人使用。当我决定封装一些方法时,我遇到了一个问题。我希望有一个内部修改器来启动并解决问题,但我找不到合适的方法来做到这一点。下面是一些代码和解释:

class SwipeLayout (...) : FrameLayout(...),
  BackgroundViewsVisibilityController, ... {
  
  private val backgroundController = BackgroundController(
        this //(BackgroundViewsVisibilityController)  
  )

  override fun revealLeftUnderView() {...}

  override fun hideLeftUnderView() {...}

  override fun revealRightUnderView() {...}

  override fun hideRightUnderView() {...}
}


interface BackgroundViewsVisibilityController {
   fun revealLeftUnderView()
   fun revealRightUnderView()
   fun hideLeftUnderView()
   fun hideRightUnderView()
}

这些是对用户隐藏的方法。我怎样才能最好地实现它?

标签: androidkotlin

解决方案


internal告诉编译器这个接口、类或函数只能从当前模块调用。当您发布一个库时,internal不能从您的库中调用该接口(不使用反射)。

您想SwipeLayout公开(供第三方使用),因此您不能同时制作接口BackgroundViewsVisibilityController internal,因为您的类正在扩展该接口。

如果您真的希望客户端不能从您的接口调用函数,请考虑没有接口(因为接口通常是供调用者使用的)但private在以下位置创建这些函数SwipeLayout

class SwipeLayout (...) : FrameLayout(...)

  private fun revealLeftUnderView() {...}
  private fun hideLeftUnderView() {...}
  private fun revealRightUnderView() {...}
  private fun hideRightUnderView() {...}
}

有关Kotlin 可见性修改器的更多信息


推荐阅读