如何改善android webview中的滚动?

时间:2018-08-22 22:20:21

标签: android performance webview scroll

我正在将网站加载到android webview中,我想提高滚动性能。换句话说,我想为用户提供更快,更流畅的滚动。有任何想法吗? 预先感谢

2 个答案:

答案 0 :(得分:0)

您是否声明要在应用程序清单中进行软件渲染(或通过设置WebView的图层类型)?也许尝试硬件模式

webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

答案 1 :(得分:0)

将WebView嵌入到Horizo​​ntalScrollView内的片段中时,我还遇到了滚动缓慢,滚动不稳定的情况,但是在其他情况下也似乎发生了这种情况。经过数天的反复试验,这似乎是可行的解决方案。关键部分是OnTouchListener;我不认为WebView设置那么重要。这是违反直觉的,但是您必须明确告诉WebView滚动...似乎是一个Android错误。

WebView myWebView;
VelocityTracker mVelocityTracker;

myWebView.setOnTouchListener(new WebViewOnTouchListener());

private class WebViewOnTouchListener implements View.OnTouchListener {
    float currY = 0;
    float yVeloc = 0f;
    WebView localWebView = myWebView;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int index = event.getActionIndex();
        int action = event.getActionMasked();
        int pointerId = event.getPointerId(index);
        switch(action){
            case MotionEvent.ACTION_DOWN:
                if (mVelocityTracker == null) {

                    // Retrieve a new VelocityTracker object to watch the velocity
                    // of a motion.
                    mVelocityTracker = VelocityTracker.obtain();
                } else {

                    // Reset the velocity tracker back to its initial state.
                    mVelocityTracker.clear();
                }
                mVelocityTracker.addMovement(event);
                currY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                mVelocityTracker.addMovement(event);
                mVelocityTracker.computeCurrentVelocity(1000);
                yVeloc = mVelocityTracker.getYVelocity(pointerId);
                float y = event.getY();
                localWebView.scrollBy(0, (int) (currY - y));
                currY = y;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                localWebView.flingScroll(0, -(int)yVeloc);
                break;

        }
        return true;
    }

}