Button onClick attribute is none if activity written in Kotlin

会有一股神秘感。 提交于 2019-12-03 04:31:00

It seems like the designer does not support Kotlin yet. Here are some solution:

XML (Not Recommended)

Add the following line to your Button tag. This is exactly what the designer will do.

android:onClick="sendMessage"

Old Fashion

No need to add anything.

val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {

}

kotlin-android-extensions (Recommended)

Add apply plugin: "kotlin-android-extensions" to your build.gradle

// button is the Button id
button.setOnClickListener {

}

Your code will like this:

button.setOnClickListener(){
            Toast.makeText(this@MainActivity, "Its toast!", Toast.LENGTH_SHORT).show();
        }

Here import will:

import kotlinx.android.synthetic.main. activity_main.*

Here "button" is the id of that Button in .xml file. Here the advantage is no need to create Button object in your java class.

Once defined the sendMessage class as :

/** Called when the user taps the Send button  */
fun sendMessage(view: View) {
    setContentView(R.layout.activity_second)
    // Do something in response to button
}

And also defined a second activity as:

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }
}

I added the SendMessage to the OnClick function:

And then it worked.

You can easily define this inside the XML itself. But using the android:onClick attribute is still a little expensive.

Instead you could consider using the Kotlin Android Extensions and synthetic properties:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener {
        // Do something in response to button
    }
}

Here's the solution I came up with in the MainActivity.kt file.

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        sendMessage()
    }
}

/** Called when the user taps the Send button  */
private fun sendMessage() {
    val editText = findViewById<EditText>(R.id.editText)
    val message = editText.text.toString()
    val intent = Intent(this, DisplayMessageActivity::class.java).apply 
    {
        putExtra(EXTRA_MESSAGE, message)
    }
    startActivity(intent)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!