2

I have a chat and I'm using Linkify to parse links and onLongClick to open a dialog that allows the user to copy the content of a message.

chatText is my TextView.

chatText.setText(message);
Linkify.addLinks(chatText, Linkify.ALL);
chatText.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
        final CharSequence[] items = {
                    "Copy"
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("Select Action");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                copyToClipboard();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;   
     }
    });

For normal messages it works fine, the problem is when I long click a linkifyed message it opens the dialog and then immediately follows the link. (e.g. opens the browser) When I get back to the app the form is still there and the copy to clipboards works just fine.

The

return true;

is supposed to block the onClick if I'm not mistaken. I can't figure out how to block the onClick whem i'm longclicking.

Jack
  • 171
  • 2
  • 16

2 Answers2

2

Here is a little class which I wrote for this case:

public class NoLongClickMovementMethod extends LinkMovementMethod {

long longClickDelay = ViewConfiguration.getLongPressTimeout();
long startTime;

private static NoLongClickMovementMethod linkMovementMethod = new NoLongClickMovementMethod();

@Override
public boolean onTouchEvent(android.widget.TextView widget, android.text.Spannable buffer, MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_DOWN) {
        startTime = System.currentTimeMillis();
    }

    if (action == MotionEvent.ACTION_UP) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - startTime >= longClickDelay)
            return true;
    }
    return super.onTouchEvent(widget, buffer, event);
}

public static android.text.method.MovementMethod getInstance() {
    return linkMovementMethod;
}

Usage: textView.setMovementMethod(NoLongClickMovementMethod.getInstance());

1

If anyone has the same problem, I found out it's a known issue of Android. One must use

    android:descendantFocusability="blocksDescendants"

in order to avoid the linkifyed textview to block other events.

Issue is reported here

https://code.google.com/p/android/issues/detail?id=3414

Jack
  • 171
  • 2
  • 16
  • not working to me, i set android:descendantFocusability="blocksDescendants" for all view but can not get longclick when longclick to textview, when textView have mention spannableString – famfamfam Mar 15 '21 at 18:45