gpt4 book ai didi

android - 在 Kotlin 中实例化接口(interface)监听器

转载 作者:行者123 更新时间:2023-11-29 14:26:19 27 4
gpt4 key购买 nike

我无法在 Kotlin 或 Kotlin for Android 中实例化 fragment 外部的接口(interface)。 Java 中的标准程序是这样说的:

MyInterface mInterfaceListener = new MyInterface(this);
mInterfaceListener.invokeSomeGenericMethod();

请注意,mInterfaceListener 指的是接口(interface),而不是 onCLickListener 或类似的东西

在 Kotlin 中如何实例化接口(interface)?如何创建一个“监听器”并触发接口(interface)的功能?

以下是我出于学习目的对一个非常简单的应用程序进行的一些尝试。注意变量mPresenterListener,它是一个接口(interface)

    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)

注意声明观察者的对象。可以对监听器执行相同的操作。

关于android - 在 Kotlin 中实例化接口(interface)监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47565553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com