Skip to main content

How to create a clickable TextView in Kotlin Android

How to create a clickable TextView in Kotlin Android.

Here is a step-by-step tutorial on how to create a clickable TextView in Kotlin for Android:

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Choose an appropriate name and package for your project.

Step 2: Layout file

In the layout file (e.g., activity_main.xml), add a TextView widget:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:textSize="18sp"
android:textColor="@android:color/black" />

Step 3: Kotlin code

In your MainActivity.kt file, initialize the TextView and set an OnClickListener on it:

class MainActivity : AppCompatActivity() {

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

val myTextView = findViewById<TextView>(R.id.myTextView)
myTextView.setOnClickListener {
// Handle click event here
// Example: show a Toast message
Toast.makeText(this, "TextView clicked!", Toast.LENGTH_SHORT).show()
}
}
}

Step 4: Handle the click event

Inside the OnClickListener, you can define the actions you want to perform when the TextView is clicked. In this example, we are showing a Toast message with the text "TextView clicked!". You can customize this part according to your needs.

Step 5: Run the app

Run the app on an emulator or a physical device to see the TextView in action. When you click on the TextView, the defined action (e.g., showing a Toast message) will be executed.

Additional Example: If you want to set a different style or behavior for the TextView when it is clicked, you can use the setOnTouchListener instead of the setOnClickListener:

class MainActivity : AppCompatActivity() {

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

val myTextView = findViewById<TextView>(R.id.myTextView)
myTextView.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
// TextView pressed
myTextView.setTextColor(Color.RED)
return@setOnTouchListener true
}
MotionEvent.ACTION_UP -> {
// TextView released
myTextView.setTextColor(Color.BLACK)
// Handle click event here
// Example: show a Toast message
Toast.makeText(this, "TextView clicked!", Toast.LENGTH_SHORT).show()
return@setOnTouchListener true
}
else -> return@setOnTouchListener false
}
}
}
}

In this example, the TextView's text color will change to red when it is pressed, and it will change back to black when released. The click event is still handled in the same way as before.

That's it! You have now created a clickable TextView in Kotlin for your Android app.