Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ClickableSpan, but ignore clicks from the TextView

Tags:

android

The following code shows how I'm applying a pressed state using a custom ClickableSpan and selector. However, the pressed state is applied whenever I press anywhere on the TextView, not just the ClickableSpan. How do I stop this?

Note: it does not call onClick, but does apply state_pressed from the selector. I want it to do neither.

MyView.java

SpannableString spanned = new SpannableString("click here");
spannable.setSpan(new MyClickableSpan() {
        @Override
        public void onClick(View widget) {
            doSomething();
        }
    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanned);
textView.setMovementMethod(LinkMovementMethod.getInstance());

MyClickableSpan.java

public abstract class MyClickableSpan extends ClickableSpan {

    @Override
    public abstract void onClick(View view);

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
    }
}

the TextView

<TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white"
    android:textColorLink="@color/my_selector" />

my_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/my_color_pressed" />
    <item android:color="@color/my_color" />
</selector>

Edit note: Added TextView code

like image 613
Fifer Sheep Avatar asked May 04 '16 16:05

Fifer Sheep


1 Answers

Next example works as you're expecting:

    Spannable span = SpannableStringBuilder.valueOf("Hello clickable span!");
    span.setSpan(new MyClickableSpan(), 6, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mTextView.setText(span);
    mTextView.setMovementMethod(LinkMovementMethod.getInstance());

Now span applied: enter image description here

Here's MyClickableSpan() that's only show Snackbar to indicate that "click" is handled:

class MyClickableSpan extends ClickableSpan {

    @Override
    public void onClick(View widget) {
        Snackbar.make(getWindow().findViewById(android.R.id.content), "Click on span!", Snackbar.LENGTH_LONG).show();
    }
}

We've got:

  1. Click/tap outside the "spanned" text will do nothing
  2. Click/tap on "spanned" part of text will show Snackbar

enter image description here

That's it. Please let me know if you need any additional info.

like image 159
Stas Lelyuk Avatar answered Oct 05 '22 03:10

Stas Lelyuk