我正在使用https://github.com/mkoslacz/Moviper作为Android Tv Box的应用。只有一个活动有多个子片段。我想仅在事件尚未处理时才将onKeyDown传播给子片段。没有使用RxJava就很容易做到。我可以返回一个布尔值来告诉事件是否已经处理过。有没有办法使用RxJava来处理它?我使用Kotlin作为源语言。这是我想要做的事情。
class MainActivity : ViperAiPassiveActivity<HomeContract.View>(), HomeContract.View {
private val keyPressSubject = BehaviorSubject.create<KeyEvent>()
private lateinit var predicate: (KeyEvent) -> Boolean
override fun keyPresses(predicate: (KeyEvent) -> Boolean): Observable<KeyEvent> {
this.predicate = predicate
return keyPressSubject
}
override fun createPresenter() = HomePresenter()
override fun getLayoutId(): Int {
return R.layout.activity_main
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
event?.run {
if (predicate(event)) {
keyPressSubject.onNext(event)
return true
}
}
return super.onKeyDown(keyCode, event)
}
}
答案 0 :(得分:1)
我最终创建了自己的事件处理程序(虽然它没有使用RxJava,但它在我的情况下完成了工作)
object KeyEventManager {
private val handlers: MutableMap<Int, (KeyEvent?) -> Boolean> = ArrayMap()
fun register(handler: (KeyEvent?) -> Boolean): Int {
val id = (handlers.keys.max() ?: 0) + 1
handlers.put(id, handler)
return id
}
fun unregister(id: Int) {
handlers.remove(id)
}
fun postEvent(event: KeyEvent?): Boolean {
for (key in handlers.keys) {
handlers.get(key)?.run {
if (invoke(event)) {
return true
}
}
}
return false
}
}