Search code examples
androidstringtextviewclickablespan

How to set the part of the text view is clickable


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

I tried but i am not getting a solution.


Solution

  • 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"
    />