主页 > 原创 > Android修改webview选中时的高亮颜色

Android修改webview选中时的高亮颜色

安卓的webview链接点击后文字会被高亮,这个颜色的修改并没有提供接口。需要处理的文件为frameworks/base/core/java/android/webkit/WebViewClassic.java,其中的setTouchHighlightRects()方法就是颜色显示的实现。通过修改其中的mTouchHightlightPaint.setColor(hit.mTapHighlightColor)可以直接修改颜色,修改后所有的触摸高亮颜色会改变。具体代码如下:

    private void setTouchHighlightRects(WebKitHitTest hit) {
        FocusTransitionDrawable transition = null;
        if (shouldAnimateTo(hit)) {
            transition = new FocusTransitionDrawable(this);
        }
        Rect[] rects = hit != null ? hit.mTouchRects : null;
        if (!mTouchHighlightRegion.isEmpty()) {
            mWebView.invalidate(mTouchHighlightRegion.getBounds());
            if (transition != null) {
                transition.mPreviousRegion = new Region(mTouchHighlightRegion);
            }
            mTouchHighlightRegion.setEmpty();
        }
        if (rects != null) {
            mTouchHightlightPaint.setColor(hit.mTapHighlightColor);
            for (Rect rect : rects) {
                Rect viewRect = contentToViewRect(rect);
                // some sites, like stories in nytimes.com, set
                // mouse event handler in the top div. It is not
                // user friendly to highlight the div if it covers
                // more than half of the screen.
                if (viewRect.width() < getWidth() >> 1
                        || viewRect.height() < getHeight() >> 1) {
                    mTouchHighlightRegion.union(viewRect);
                } else if (DebugFlags.WEB_VIEW) {
                    Log.d(LOGTAG, "Skip the huge selection rect:"
                            + viewRect);
                }
            }
            mWebView.invalidate(mTouchHighlightRegion.getBounds());
            if (transition != null && transition.mPreviousRegion != null) {
                transition.mNewRegion = new Region(mTouchHighlightRegion);
                mFocusTransition = transition;
                ObjectAnimator animator = ObjectAnimator.ofFloat(
                        mFocusTransition, "progress", 1f);
                animator.start();
            }
        }
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注