In my application, I have implemented a WebView
to load local html
content and then call a JavaScript
function to scroll the WebView
to a specific position. Here is how I achieve this functionality:
public class MyActivity extends Activity {
private WebView web1;
private int ID;
private MyWebViewClient webViewClient1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// Retrieve the ID of the content to be loaded.
ID = getIntent().getIntExtra("element_id", 1);
web1 = (WebView) findViewById(R.id.web1);
web1.getSettings().setJavaScriptEnabled(true);
// Initialize the webViewClients.
webViewClient1 = new MyWebViewClient(true);
web1.setWebViewClient(webViewClient1);
displayArticle(web1);
}
private void displayArticle (WebView wv) {
StringBuilder sb = new StringBuilder();
// Code for constructing the HTML String.
String finalHtml = sb.toString();
wv.loadDataWithBaseURL("file:///android_asset/html/", finalHtml, "text/html", "UTF-8", null);
}
private class MyWebViewClient extends WebViewClient {
String urlToLoad;
MyWebViewClient (boolean setUrlToLoad) {
if (setUrlToLoad) {
setUrlToLoad();
}
}
public void setUrlToLoad () {
this.urlToLoad = "javascript:(function () {" +
"var elem = document.getElementById('e"+ID+"');" +
"var x = 0;" +
"var y = 0;" +
"while (elem != null) {" +
"x += elem.offsetLeft;" +
"y += elem.offsetTop;" +
"elem = elem.offsetParent;" +
"}" +
"window.scrollTo(x, y);" +
"})()";
}
@Override
public void onPageStarted (WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("Pages", "Page loading started");
}
@Override
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.d("Pages", "Webview content load error");
}
@Override
public void onPageFinished (WebView view, String url) {
super.onPageFinished(view, url);
Log.d("Pages", "Page loading finished");
if (urlToLoad != null) {
// Scroll to the designated position.
view.loadUrl(urlToLoad);
urlToLoad = null;
}
}
}
}
In the provided code snippet, after triggering the callback functions in the MyWebViewClient
class using wv.loadDataWithBaseURL
within the displayArticle(WebView wv)
function, subsequent loadUrl
calls do not elicit another round of callbacks from MyWebViewClient
upon completion of the request in onPageFinished
. This behavior persists even with other loadUrl
invocations on the same WebView
.
I am seeking insights into why this phenomenon occurs and would greatly appreciate any clarifications.