TextView OnClickListener in Kotlin Android
In Android, TextView is a child class of View, and hence can use the method setOnClickListener() on the object of TextView.
In this tutorial, we will learn how to set OnClickListener for TextView in Kotlin file, with the help of an example.
Code – TextView OnClickListener
Following is quick look into code to set OnClickListener for TextView in Kotlin Programming :
// get reference to textview
val tv_click_me = findViewById(R.id.tv_click_me) as TextView
// set on-click listener
tv_click_me.setOnClickListener {
// your code to run when the user clicks on the TextView
}
Example – OnClickListener for TextView
In this example, we shall look into the layout xml file and Activity(Kotlin file) to set OnClickListener for a TextView.
Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content.
activity_main.xml
We have a TextView in LinearLayout. We will use this TextView to set on-click listener.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tutorialkart.myapplication.MainActivity">
<LinearLayout
android:id="@+id/ll_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tv_click_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:text="Click Me"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.kt
Get reference to the the TextView in layout file using id, and then call setOnClickListener {} on this TextView. When user clicks on this TextView, the code inside setOnClickListener {} will be executed.
package com.tutorialkart.myapplication
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get reference to textview
val tv_click_me = findViewById(R.id.tv_click_me) as TextView
// set on-click listener
tv_click_me.setOnClickListener {
// your code to perform when the user clicks on the TextView
Toast.makeText(this@MainActivity, "You clicked on TextView 'Click Me'.", Toast.LENGTH_SHORT).show()
}
}
}
Following are the screenshots to demonstrate the setOnClickListener for TextView.
Conclusion
In this Kotlin Android Tutorial, we have learnt how to set on-click listener for TextView using TextView.setOnClickListener() method.