How to set the part of the Android TextView as clickable - ClickableSpan
Published February 16, 2020In this example we are going to create how to set the part of the Android TextView as clickable.
Step 1 : Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 : Add the following code to activity_spanable_click_textview.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please CLICK this TO play some thing"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold|italic"/>
</RelativeLayout>
|
Step 3: Update SpanableClickTextview.kt with below clode
package com.rrtutors.androidsamples
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_spanable_click_textview.*
class SpanableClickTextview : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_spanable_click_textview)
var text = "Please CLICK this TO play some thing";
var spannableString = SpannableString(text);
var clickableSpan1 = object: ClickableSpan(){
override fun onClick(widget: View) {
Toast.makeText(this@SpanableClickTextview, "CLICK", Toast.LENGTH_SHORT).show();
}
}
var clickableSpan2 = object: ClickableSpan(){
override fun onClick(widget: View) {
Toast.makeText(this@SpanableClickTextview, "TO", Toast.LENGTH_SHORT).show();
}
}
spannableString.setSpan(clickableSpan1, 7,12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(clickableSpan2, 18,20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
|
Step 4: Let's run the application
Article Contributed By :
|
|
|
|
1344 Views |