Android multiple WebViews Issue: Not being able to load the first one until the rest have loaded
I have an activity that stores 5 WebViews
in a ViewFlipper
. It only shows one at a time. In the onCreate() of my activity I'm loading the first WebView on my main thread and the others in a background thread.
What I was expecting was to see the WebView
right away while the others were still loading. What I found is that the first WebView
i perform a loadData()
with finishes last. I found this by setting a WebChromClient
and checking the onProgressChanged()
. The first WebView always seems to load last.
I'm assuming the WebView.loadData() function works asynchronously, but I have no idea why the first one I load always finishes last, not ever 2nd, 3rd, 4th or 1st, but 5th, which is last in my case.
Does anyone know why?
Here's some example code:开发者_StackOverflow中文版
Setting up my WebViews
for( int i = 0; i < 5; i++ ){
WebView tempWebView = new WebView(this);
tempWebView.setWebChromeClient( new MyWebChromClient( i ) );
mFlipper.addView(tempWebView);
}
( (WebView)mFlipper.getChildAt(0) ).loadData( content, "text/html", "UTF-8" );
// load the others now in a background thread...
Here's my WebChromClient
private class MyWebChromClient extends WebChromeClient{
private int webViewId;
public MyWebChromClient( int viewFlipperChildNum ){
webViewId = viewFlipperChildNum;
}
public void onProgressChanged(WebView view, int newProgress) {
if( newProgress == 100 )
Log.i("ChromClient", "WebView Id: " + webViewId + "Progress changed: " + newProgress );
};
}
Well, after poking around a bit I really never understood why the first WebView was getting loaded last, but I did come up with a solution for myself. What I did, is I loaded the first WebView that we be shown all alone. Then, in the onProgressChanged( WebView view, int newProgress) function i load the rest of the WebViews in the background.
Example code:
private class MyWebChromClient extends WebChromeClient{
private int webViewId;
public MyWebChromClient( int viewFlipperChildNum ){
webViewId = viewFlipperChildNum;
}
public void onProgressChanged(WebView view, int newProgress) {
if( newProgress == 100 ){
//load other WebViews now that the first one is finished!
}
};
}
精彩评论