Android:在textview中使用javascript

时间:2016-02-21 06:01:02

标签: javascript android html

我有一个视图寻呼机,每个页面都有一个textview,我在我的textview中解析了html文件(没有javascript ),我在这个文档里面有很多锚标签,我想调用JavaScript函数在锚标签中单击。例如,

<a class="pginternal" tag="{http://www.w3.org/1999/xhtml}a" onclick="GoToPageNumber(186)" style="color:Blue !important;cursor:pointer !important;text-decoration:underline !important">THE VAMPIRE'S SIXTH STORY — In Which Three Men Dispute about a Woman.</a>

有“GoToPageNumber”事件,如何更改此处点击的寻呼机项目位置。

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。将移动方法设置为textview。

textview.setMovementMethod(LinkMovementMethodExt.getInstance());

public static class LinkMovementMethodExt extends LinkMovementMethod 
{
    private static LinkMovementMethod sInstance;

    public static MovementMethod getInstance()
    {
        if (sInstance == null)
        {
            sInstance = new LinkMovementMethodExt();
        }
        return sInstance;
    }

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

        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) 
        {
            try {
                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 currentLine = layout.getLineForVertical(y);
                int totalLine = layout.getLineCount();
                off = layout.getOffsetForHorizontal(currentLine, x);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                URLSpan[] urls = buffer.getSpans(off, off+1, URLSpan.class);
                for(URLSpan span : urls) 
                {
                    String urlStr = span.getURL();

                    Log.v("URL SPAN", urlStr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}

答案 1 :(得分:0)

您无法在TextView中运行JavaScript。您将不得不使用单击侦听器在Java中执行所有操作。如果只想单击TextView中的链接,则需要了解如何使用Spannable。您可以获得here的帮助。