How to work around the delayed/slow WebView render

2020-07-18 06:08发布

问题:

When utilizing a WebView to display simple formatted text (no remote content loading), some devices like the Nexus 4 or Galaxy Nexus have a very notable delay between onPageFinished() and actually displaying the text. If the WebView is used in a dynamic vertical layout with it's height set to wrap_content, all elements below will visibly jump down and hence create a very bad user experience.

For example:

public class WebViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        WebView webview = (WebView) findViewById(R.id.webview);
        webview.loadData("<html><head></head><body>WebView rendering is slow on some devices like the Nexus 4!</body></html>", "text/html", "utf-8");
    }
}

With R.layout.activity_web_view being

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#AAA" >

    <WebView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/webview"/>

    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_margin="5dp"
        android:text="Elements below the WebView are jumping down when rendering is completed."/>
</LinearLayout>

A demo project with this code can be found at https://github.com/rodja/webview-slow-rendering-demo

How can I best work around this issue? Speed up tips I found on StackOverflow seems not to help. Is hiding the whole LayoutGroup until rendering is done the only option?