Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make webviews as large as its content?

I couldn't find this on the web. I have many webviews in a HorizontalScrollView, I want all of them fit its content (then potentially have a different width ). More, I inflate those webviews like this:

LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.webview_holder, null);
webView =  (WebView) layout.findViewById(R.id.webView);
webView.loadData(data, "text/html; charset=UTF-8", "UTF-8");
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(true);
pageHolder.addView(layout);

The "page holder" layout :

<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">

    <HorizontalScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/page_holder"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

and then the "webview layout" :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">
    <WebView 
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
</LinearLayout>
like image 989
user1885718 Avatar asked Jan 15 '23 10:01

user1885718


1 Answers

The problem with wrap_content and WebViews is that the rendering of the webpage is async from layouting in the view hierarchy. When Android measures the size of the webviews to determine where to place them in the LinearLayout, the pages may not have been rendered and hence the width is 0. You need to add a PictureListener to each WebView and determine when all onNewPicture(WebView, Picture) callbacks have been called. Then you can call requestLayout() on your LinearLayout to schedule a layout pass.

like image 58
Rodja Avatar answered Jan 18 '23 23:01

Rodja