在Kotlin中实例化接口侦听器

时间:2017-11-30 03:48:14

标签: android interface kotlin

在我的生活中,我无法在Kotlin或Kotlin for Android中实例化片段之外的界面。用Java来说这是标准的程序:

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

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

如何在Kotlin中实例化接口?我如何成为一个"听众"并触发界面功能?

以下是我为学习目的而做的一个非常简单的应用程序的一些尝试。注意变量 mPresenterListener 是一个接口

    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()
}

}

2 个答案:

答案 0 :(得分:6)

你可以像这样做观察者/听众:

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)

注意声明观察者的对象。可以和听众一样做。

答案 1 :(得分:0)

此外,我们可以使用没有某些界面的监听器,默认值如下:

val someButtonListener: (isChecked: Boolean) -> Unit = {_ -> }
val someButtonListener: (v: View) -> Unit = {_ -> }