How to set the part of the text view is clickable

naresh picture naresh · May 22, 2012 · Viewed 135.1k times · Source

I have the text "Android is a Software stack". In this text i want to set the "stack" text is clickable. in the sense if you click on that it will redirected to a new activity(not in the browser).

I tried but i am not getting.

Answer

dira picture dira · May 22, 2012

android.text.style.ClickableSpan can solve your problem.

SpannableString ss = new SpannableString("Android is a Software stack");
ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        startActivity(new Intent(MyActivity.this, NextActivity.class));
    }
    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
    }
};
ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);

In XML:

<TextView 
  ...
  android:textColorLink="@drawable/your_selector"
/>