继承InputConnection接口时无法访问抽象成员,如何正确实现?
错误原因与解决方案
错误1:存在未重写的接口成员
InputConnection是包含多个抽象方法的接口,Kotlin要求实现接口时必须重写所有抽象方法。你只实现了getTextBeforeCursor这一个方法,其余未实现的抽象成员导致了该报错。
错误2:无法直接访问抽象成员
接口中的抽象方法没有具体实现逻辑,super.getTextBeforeCursor(...)本质是试图调用一个不存在的实现,自然会报错。接口的super调用仅适用于带有默认实现的方法,而InputConnection的getTextBeforeCursor是纯抽象方法。
正确实现方式
Android官方提供了BaseInputConnection类,它是InputConnection的默认实现类,已封装大部分方法的基础逻辑,你只需重写需要定制的方法即可,这是最常用的方案:
// 类名首字母大写符合Kotlin规范 class Meow(private val targetInputConnection: InputConnection) : BaseInputConnection(targetInputConnection, true) { override fun getTextBeforeCursor(before: Int, after: Int): CharSequence? { // 在这里编写自定义逻辑,或直接调用父类实现 return super.getTextBeforeCursor(before, after) } }
如果一定要直接实现InputConnection接口,必须重写所有抽象方法,示例(仅演示,不推荐):
class Meow : InputConnection { override fun getTextBeforeCursor(before: Int, after: Int): CharSequence? { // 编写自己的实现逻辑,不能调用super return "" // 示例返回空字符串,根据需求调整 } // 必须重写InputConnection的所有其他抽象方法,比如: override fun getTextAfterCursor(length: Int, flags: Int): CharSequence? = null override fun getSelectedText(flags: Int): CharSequence? = null override fun setSelection(start: Int, end: Int): Boolean = false // 剩余所有抽象方法都需要类似实现 }
内容的提问来源于stack exchange,提问作者Allo Moondragon
相关产品推荐
相关产品推荐

