注册OnBackPressedCallback()方法来处理返回手势
// BackPressed.kt
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
fun AppCompatActivity.onBackPressed(isEnabled: Boolean, callback: () -> Unit) {
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(isEnabled) {
override fun handleOnBackPressed() {
callback()
}
})
}
使用示例:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(...)
// 返回手势处理
onBackPressed(true){
closApp()
}
}
}
使用Kotlin委托和Java动态代理实现移除接口需要强制实现的方法
// RemoveUnnecessaryFun.kt
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
inline fun <reified T : Any> noOpDelegate(): T {
val javaClass = T::class.java
return Proxy.newProxyInstance(
javaClass.classLoader, arrayOf(javaClass), noOpHandler
) as T
}
val noOpHandler = InvocationHandler { _, _, _ ->
// no op
}
使用示例:
// 示例一
animation.setAnimationListener(object : Animation.AnimationListener by noOpDelegate() {
//实现自己想要实现的方法即可
override fun onAnimationEnd(animation: Animation) {
animation.cancel()
}
})
// 示例二
viewpage.addOnPageChangeListener(object : OnPageChangeListener by noOpDelegate() {
override fun onPageSelected(position: Int) {
// ......
}
})
// 示例三
editText.addTextChangedListener(object : TextWatcher by noOpDelegate(){
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// 处理内容变化
}
})