activity_main.xmlMainActivity.java
<?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.codinginflow.clickablespanexample.MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I want THIS and THIS to be clickable" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
package com.codinginflow.clickablespanexample; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.TextPaint; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); String text = "I want THIS and THIS to be clickable"; SpannableString ss = new SpannableString(text); ClickableSpan clickableSpan1 = new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, "One", Toast.LENGTH_SHORT).show(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(Color.BLUE); ds.setUnderlineText(false); } }; ClickableSpan clickableSpan2 = new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, "Two", Toast.LENGTH_SHORT).show(); } }; ss.setSpan(clickableSpan1, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(clickableSpan2, 16, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ss); textView.setMovementMethod(LinkMovementMethod.getInstance()); } }