在Kotlin中实例化接口监听器
在我的生活中,我不能在Kotlin或Kotlin for Android中实例化一个片段之外的接口。 在Java中这是一个标准的过程,可以这样说:
MyInterface mInterfaceListener = new MyInterface(this); mInterfaceListener.invokeSomeGenericMethod();
请注意,mInterfaceListener指的是一个接口,而不是onCLickListener或类似的东西
接口如何在Kotlin中实例化? 我如何做一个“侦听器”并触发一个接口的function?
下面是一些非常简单的应用程序,我正在做的学习目的。 注意variablesmPresenterListener是一个接口
class QuoteActivity : QuoteContract.ViewOps, AppCompatActivity() { private lateinit var vText: TextView private lateinit var vFab: FloatingActionButton private lateinit var mPresenterListener: QuoteContract.PresenterOperations override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mPresenterListener = this.mPresenterListener vText=findViewById(R.id.main_quote) vFab=findViewById(R.id.main_fab) vFab.setOnClickListener{ mPresenterListener.onQuoteRequested() } } override fun displayQuote(quote: String) { vText.text = quote } }
而我的主持人:
class QuotePresenter(private val viewListener: QuoteContract.ViewOps): QuoteContract.PresenterOperations { private lateinit var modelListener: QuoteContract.ModelOperations init { modelListener = this.modelListener } override fun onQuoteRequested() { modelListener.generateQuote() } override fun onQuoteGenerated(quote: String) { viewListener.displayQuote(quote) } }
界面:
interface QuoteContract { //Methods available to Presenter (Presenter -> View) interface ViewOps{ fun displayQuote(quote: String) } //Ops offered from presenter to view (Presenter->View) interface PresenterOperations { //Presenter->View fun onQuoteRequested() //Presenter->Model fun onQuoteGenerated(quote: String) } //Ops offered from Model to Presenter (Model -> Presenter) interface ModelOperations { fun generateQuote() }
}
你可以做这样的观察者/听众:
val textView: TextView = this.findViewById(R.id.amountEdit) val watcher = object : TextWatcher { override fun afterTextChanged(p0: Editable?) { val inputAmount = textView.text.toString val amount = if (!inputAmount.isEmpty()) inputAmount.toDouble() else 0.0 conversionViewModel?.convert(amount) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { println("before text changed called..") } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { println("text changed..") } }
接着:
textView.addTextChangedListener(watcher)
注意在宣布观察者的对象。 可以做一个监听器一样的。