1

How do I click on use kotlin?

In java I did using the findviewbyid and setonclicklistener

How would that be in Kotlin on Android?

Luhhh
  • 129
  • 2
  • 1
    Possible duplicate of [Button onClick attribute is none if activity written in Kotlin](https://stackoverflow.com/questions/46970565/button-onclick-attribute-is-none-if-activity-written-in-kotlin) – da vamp Sep 27 '18 at 04:00

3 Answers3

1

No need of findViewById : you can refer to your Views by their IDs via the synthetic properties of 'kotlin-android-extensions' line in your module level build.gradle file.

build.gradle(app) file in your project : apply plugin: 'kotlin-android-extensions'

Then in your xml file:

<android:id="@+id/tvForgotPsw"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Forgot your password"/>

Lastly in your .kt file you simply need to use view ids and their properties:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)

    tvForgotPsw.setOnClickListener(object : View.OnClickListener{
        override fun onClick(p0: View?) {
        }
    })
}
Nikita
  • 65
  • 5
0

The same exact way. Kotlin isn't that different. It just has lambdas:

val view = findViewById<SomeViewClass>(R.id.some_id)
view.setOnClickListener {
    //"it" is the clicked View
}

You can even paste Java code into your IDE and it will convert it to Kotlin for you.

You could also read the docs.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
0

In kotlin, you don't need findViewById(). You can use kotlin extensions and it has synthetic binding

For click listener, unlike java you don't need anonymous implementations of the interface

view.setOnClickListener({ v -> toast("Hello") })

Prasanna Narshim
  • 778
  • 10
  • 14