Luhhh
Luhhh

Reputation: 111

ClickListener in Kotlin Android x Java

How do I click on use kotlin?

In java I did using the findviewbyid and setonclicklistener

How would that be in Kotlin on Android?

Upvotes: 1

Views: 267

Answers (3)

Nikita
Nikita

Reputation: 65

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?) {
        }
    })
}

Upvotes: 1

Prasanna Narshim
Prasanna Narshim

Reputation: 798

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

Upvotes: 0

TheWanderer
TheWanderer

Reputation: 17824

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.

Upvotes: 0

Related Questions