LinkMovementClickMethod.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.xzjmyk.pm.activity.util;
  2. import android.text.Layout;
  3. import android.text.Selection;
  4. import android.text.Spannable;
  5. import android.text.method.LinkMovementMethod;
  6. import android.text.style.ClickableSpan;
  7. import android.view.MotionEvent;
  8. import android.widget.TextView;
  9. public class LinkMovementClickMethod extends LinkMovementMethod{
  10. private long lastClickTime;
  11. private static final long CLICK_DELAY = 500l;
  12. @Override
  13. public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
  14. int action = event.getAction();
  15. if (action == MotionEvent.ACTION_UP ||
  16. action == MotionEvent.ACTION_DOWN) {
  17. int x = (int) event.getX();
  18. int y = (int) event.getY();
  19. x -= widget.getTotalPaddingLeft();
  20. y -= widget.getTotalPaddingTop();
  21. x += widget.getScrollX();
  22. y += widget.getScrollY();
  23. Layout layout = widget.getLayout();
  24. int line = layout.getLineForVertical(y);
  25. int off = layout.getOffsetForHorizontal(line, x);
  26. ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
  27. if (link.length != 0) {
  28. if (action == MotionEvent.ACTION_UP) {
  29. if(System.currentTimeMillis() - lastClickTime < CLICK_DELAY){
  30. link[0].onClick(widget);
  31. }
  32. } else if (action == MotionEvent.ACTION_DOWN) {
  33. Selection.setSelection(buffer,
  34. buffer.getSpanStart(link[0]),
  35. buffer.getSpanEnd(link[0]));
  36. lastClickTime = System.currentTimeMillis();
  37. }
  38. return true;
  39. } else {
  40. Selection.removeSelection(buffer);
  41. }
  42. }
  43. return super.onTouchEvent(widget, buffer, event);
  44. }
  45. public static LinkMovementClickMethod getInstance(){
  46. if(null == sInstance){
  47. sInstance = new LinkMovementClickMethod();
  48. }
  49. return sInstance;
  50. }
  51. private static LinkMovementClickMethod sInstance;
  52. }