Issue
I am writing an Android app that uses a WebView to display content. The main purpose of the app is to display text for a user to read.
I am dynamically adding HTML to my WebView via JavaScript. When adding content to the bottom of the page it is not a problem. when adding content to the top, the WebView automatically scrolls to the top. That's my problem.
I need to try and find a way to prevent my WebView from automatically scrolling to the top of the page when content is added to the top.
I do have some limitations though:
1) I am using JavaScript, but am unable to use jQuery.
2) I am currently confined to Android API 8 (v2.2).
3) I don't want to just scroll back to my original position. (I have found many solutions on SO for this issue in which I would just programatically scroll back to my position before the scroll. I have a current implementation of this, but it is not a smooth enough transition.)
4) I need to allow the user to continuously scroll upward while content is being added. (While I am open to an implementation of disabling scrolling to prevent the WebView from scrolling itself back up, I need to allow the user to keep scrolling up while I am adding content a screen's height or so above them.)
Sorry if this seems confining, but you can see why I needed some advice.
Many thanks in advance.
Solution
I found a way around my problem. If anyone has another, especially a more direct, answer I would still be interested.
I was, in part, mis-diagnosing my problem. When I add HTML using: document.body.insertBefore(newDiv, topDiv.nextSibling);
, I add my new HTML just below the top edge of the document.
I thought I was scrolling back up to the top of the screen (co-ordinates [0,0]), but instead the document length was changing and my current Y position stayed the same. So the co-ordinates I was viewing were constant, but the HTML those co-ordinates displayed changed. The effect was "scrolling up" the page.
I ended up adding a HUGE div of white space above my visible text. Every time I add HTML it shrinks by the exact height of the added HTML. This offsets the added text, allowing my visible screen to stay the exact same. This means NO scrolling, which is a much more fluid UI.
This gives a whole different set things to work around, like stopping the user from scrolling the whole length of my white space and ensuring I don't make my WebView larger than my max size. The trade-offs are well worth it though, as the user experience is drastically improved.
Answered By - Jon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.