handle textview link click in my android app

前端 未结 12 925
迷失自我
迷失自我 2020-11-22 04:33

I\'m currently rendering HTML input in a TextView like so:

tv.setText(Html.fromHtml(\"test\"));

The HTML b

12条回答
  •  攒了一身酷
    2020-11-22 05:00

    if there are multiple links in the text view . For example textview has "https://" and "tel no" we can customise the LinkMovement method and handle clicks for words based on a pattern. Attached is the customised Link Movement Method.

    public class CustomLinkMovementMethod extends LinkMovementMethod
    {
    
    private static Context movementContext;
    
    private static CustomLinkMovementMethod linkMovementMethod = new CustomLinkMovementMethod();
    
    public boolean onTouchEvent(android.widget.TextView widget, android.text.Spannable buffer, android.view.MotionEvent event)
    {
        int action = event.getAction();
    
        if (action == MotionEvent.ACTION_UP)
        {
            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);
    
            URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
            if (link.length != 0)
            {
                String url = link[0].getURL();
                if (url.startsWith("https"))
                {
                    Log.d("Link", url);
                    Toast.makeText(movementContext, "Link was clicked", Toast.LENGTH_LONG).show();
                } else if (url.startsWith("tel"))
                {
                    Log.d("Link", url);
                    Toast.makeText(movementContext, "Tel was clicked", Toast.LENGTH_LONG).show();
                } else if (url.startsWith("mailto"))
                {
                    Log.d("Link", url);
                    Toast.makeText(movementContext, "Mail link was clicked", Toast.LENGTH_LONG).show();
                }
                return true;
            }
        }
    
        return super.onTouchEvent(widget, buffer, event);
    }
    
    public static android.text.method.MovementMethod getInstance(Context c)
    {
        movementContext = c;
        return linkMovementMethod;
    }
    

    This should be called from the textview in the following manner:

    textViewObject.setMovementMethod(CustomLinkMovementMethod.getInstance(context));
    

提交回复
热议问题