android span点击事件

时间:2013-03-29 08:01:38

标签: android position tooltip html clickable

确定。这些是我的问题。

  1. 我需要使用正则表达式来输出除字母之外的所有内容,然后我需要将找到的单词包含在$ word标签中。 使用此str = str.replaceAll(pattern,“$ 0”);. 现在我正在过滤所有正确的元素(标点符号,数字等),但它包含了一个标签中每个单词中的每个字母而不是单词。那么如何使用正则表达式将字母分组为单词?
  2. from“(标签打开)t(关闭)(标签打开)h(关闭)(标签打开)i(关闭)(标签打开)s(关闭)(标签打开) i(关闭)(标签打开)s(关闭)(标签打开)w(关闭)(标签打开)r(关闭)(标签打开)o(关闭)(标签打开) n(关闭)(标签打开)g(关闭)“;

    到:

    “(标签打开)此(关闭)(标签打开)是(关闭)(标签打开)右(关闭)”;

    然后我让它们可点击,我需要抓住点击事件并在点击的单词上获得屏幕上的位置,因为我想使用点击的事件使工具提示显示在点击的单词下方。谢谢你的帮助。

    公共类MainActivity扩展了Activity {

    public String text = "This is just a sentence to test you. 23 this is another number23!g?";
    public TextView tv;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        text = explode(text);
    
        tv = (TextView) findViewById(R.id.tv1);
    
        tv.setLinksClickable(true);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    
        Spanned article = Html.fromHtml(text, null, null);
        setHTML(article);
    }
    
    
    public void setHTML(Spanned html) {
          SpannableString message = new SpannableString(html.toString());
          Object[] spans = html.getSpans(0, html.length(), Object.class);
          for (Object span : spans) {
             int start = html.getSpanStart(span);
             int end = html.getSpanEnd(span);
             int flags = html.getSpanFlags(span);
             if (span instanceof URLSpan) {
                URLSpan urlSpan = (URLSpan) span;
                span = new CallbackSpan(urlSpan.getURL());
             }
             message.setSpan(span, start, end, flags);
          }
          tv.setText(message);
       }
        public String explode(String str){  
          String pattern = "([a-zA-Z])";
          str = str.replaceAll(pattern, "<a href=\"$0\">$0</a>");
          return str;
        }
    
       private final class CallbackSpan extends ClickableSpan {
    
          private String m_data;
          private String url_main;
    
          public CallbackSpan(String url) {
             m_data = url.substring(0);
             url_main = url;
    
          }
    
          public void onClick(View view) {
    
              TextView item = (TextView)findViewById(R.id.tv2);
              item.setText(url_main + " was clicked.");
              Log.d("item", url_main);
          }
       }
    

    }

2 个答案:

答案 0 :(得分:8)

最新代码,请参阅link form github

message.setSpan(span, start, end, flags);

在设置新范围之前,您需要删除原始范围。 请看下面
The onClick() of ClickableSpan is not working for URLSpan?

EDIT
您可以extends LinkMovementMethod

捕获任意跨度点击事件
    import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.TextView;

import java.lang.ref.WeakReference;

public class LinkMovementMethodExt extends LinkMovementMethod {
    public static final int LinkMovementMethod_Down = 1001;
    public static final int LinkMovementMethod_Up = 2002;
    private static LinkMovementMethod sInstance;
    private Class mSpanClass = null;
    private WeakReference<Handler> mWeakReference = null;

    public static MovementMethod getInstance(Handler handler, Class spanClass) {
        if (sInstance == null) {
            sInstance = new LinkMovementMethodExt();
            ((LinkMovementMethodExt) sInstance).mWeakReference = new WeakReference<>(handler);
            ((LinkMovementMethodExt) sInstance).mSpanClass = spanClass;
        }
        return sInstance;
    }

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

        if (action == MotionEvent.ACTION_UP ||
                action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);
            /**
             * get you interest span
             */
            Object[] spans = buffer.getSpans(off, off, mSpanClass);
            if (spans.length != 0) {
                if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer, buffer.getSpanStart(spans[0]), buffer.getSpanEnd(spans[0]));
                    MessageSpan obj = new MessageSpan();
                    obj.setObj(spans);
                    obj.setView(widget);
                    Handler handler = mWeakReference.get();
                    if (handler != null) {
                        Message message = handler.obtainMessage();
                        message.obj = obj;
                        message.what = LinkMovementMethod_Down;
                        message.sendToTarget();
                        return true;
                    }
                    return false;
                } else if (action == MotionEvent.ACTION_UP) {
                    Handler handler = mWeakReference.get();
                    if (handler != null) {
                        MessageSpan obj = new MessageSpan();
                        obj.setView(widget);
                        Message message = handler.obtainMessage();
                        message.obj = obj;
                        message.what = LinkMovementMethod_Up;
                        message.sendToTarget();
                        return true;
                    }
                    return false;
                }
            }
        }

        return super.onTouchEvent(widget, buffer, event);
    }

    public boolean canSelectArbitrarily() {
        return true;
    }

    public boolean onKeyUp(TextView widget, Spannable buffer, int keyCode,
                           KeyEvent event) {
        return false;
    }

<强> textView.setMovementMethod(LinkMovementMethodExt.getInstance());


编辑“android developer”
LinkMovementMethodExt 类添加处理程序属性是更好的方法。
您可以捕获作为Message对象传递的所有Spanned。

onTouchEvent方法中的剪辑代码:

Message message = Handler.obtainMessage();
message.obj = buffer.getSpans(off, off, Spanned.class);//get all spanned
message.what = 111;//which value ,it is up to you
message.sendToTarget(); //send message to you target handler

您可以在处理程序类中处理预期的跨区域。可能是灵活的处理方式 希望能帮到你。


enter image description here


textview文本上方是<a href='/a'>aaaa</a>123456<a href='/b'>bbbb</b>7890
我理解你的要求:
点击'aaaa',你想得到它s href value '/a', click 'bbbb',get it s href'/ b';不要触发在Web浏览器中打开的默认操作。
如果我理解是对的,你可以这样做:

  • 为textview等设置LinkMovementMethod:textview.setMovementMethod(LinkMovementMethodExt.getInstance(handler, URLSpan.class));
  • 获得兴趣范围,这里是URLSpan 在处理程序 handleMessage 方法中,您可以这样做:
private Handler handler = new Handler() {
      public void handleMessage(Message msg) {
          int what = msg.what;
          if (what == 100) {
              Object[] spans = (Object[])msg.obj;
              for (Object span : spans) {
                  if (span instanceof URLSpan) {
                      System.out.println(((URLSpan) span).getURL());
                  }
              }
          }
      };
  };

Download demo code

  • MainActivity 具有颜色属性,您可以根据需要指定哪个颜色值。

怎么办?

  • Step1,获取当前点击范围。

  • Step2,将BackgroundColorSpan设置为当前点击范围

答案 1 :(得分:0)

假设您想要在textview上单击单个单词?我不明白你的评论中所有字母转换为单词。

以下内容可用于点击单个作品,并以祝酒词显示。

    public class MainActivity extends Activity {

    TextView _tv;
    String[] each;
    SpannableString ss1;
    Button b;
    EditText et;
    String s;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b= (Button) findViewById(R.id.button1);
    et = (EditText) findViewById(R.id.ed);
    _tv = (TextView) findViewById( R.id.tv );
    b.setOnClickListener(new OnClickListener()
    {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        s=et.getText().toString();
        _tv.setText("");
        for(int i=0;i<s.length();i++)
        {
            each = s.split("\\s+");
        }
        for(int i=0;i<each.length;i++)
        {
            System.out.println("................"+each[i]);
            ss1=  new SpannableString(each[i]);
            //StyleSpan boldSpan = new StyleSpan( Typeface.BOLD );
            //spannable.setSpan( boldSpan, 41, 52, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
            ss1.setSpan(new MyClickableSpan(each[i]), 0, ss1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            _tv.append(ss1); 
            _tv.append(" "); 

        }
        _tv.setMovementMethod(LinkMovementMethod.getInstance());
    }
       });
      }
      class MyClickableSpan extends ClickableSpan{ 
      String clicked;
          public MyClickableSpan(String string) {
    // TODO Auto-generated constructor stub
       clicked =string;
      }
      //clickable span
      public void onClick(View textView) {
      //do something


      Toast.makeText(MainActivity.this,clicked ,
        Toast.LENGTH_SHORT).show();
     }
     @Override
     public void updateDrawState(TextPaint ds) {
     ds.setColor(Color.BLACK);//set text color 
     ds.setUnderlineText(false); // set to false to remove underline
     }
    }
    }