我们知道,在android studio中,我们可以为一个对话框或者一个片段创建不同的监听器,并通过实现这些监听器在前面的活动中使用。
但是,当这个过程的数量增加时,活动就会变得过于臃肿,可能会出现代码难以辨认的糟糕情况。
通常是这样做的,但可能有不同的方法。针对这种情况,你是否可以提出不同的方法呢?
下面是一个java代码的例子。我可以得到你对Kotlin或Java的建议。这两种方案都很有用。
public class MainActivity extends BaseControlActivity implements SearchAutoCompleteView.AutoTextControlListener,
PlateListener, DrawerLayout.DrawerListener, AnimalListener,
GenderDialog.GenderDialogListener, NotifiyManager.NotifyListener,
OpenDialog.OpenADialogListener, MainActivityListener, CodeListener {
}
答案是授权。Kotlin有很棒的授权工具。
如果Listeners都被接口很好的顶了起来,那么你可以分别实现每个接口,并保持每个接口的逻辑很好的分割。我在下面附上了一些玩具代码,如果你有这种情况,也有一些共享状态。
interface MyAPI1 {
fun doSomething1()
}
interface MyAPI2 {
fun doSomething2()
}
class MyImplementation1(val state: SomeSharedState) : MyAPI1 {
override fun doSomething1() {
TODO("Not yet implemented")
}
}
class MyImplementation2(val state: SomeSharedState) : MyAPI2 {
override fun doSomething2() {
TODO("Not yet implemented")
}
}
data class SomeSharedState(
val arbitrary: String
)
/**
* Here we have the do everything class that combines all interfaces and implementations into one class.
* It also passes the shared state to each delegated implementation.
*/
class MyDoEverythingImplementation(state: SomeSharedState) :
MyAPI1 by MyImplementation1(state),
MyAPI2 by MyImplementation2(state)