Webview With Anchors Inside Nestedscrollview
I have a NestedScrollView with a WebView inside. The WebView contains an HTML file with anchors, that are linked to the same file but difference places (imagine 'menu' and 'content
Solution 1:
I got anchors to work by calculating their position with Javascript inside the WebView
and then programmatically scrolling the NestedScrollView
by calling a custom URL and catching it with the WebViewClient
. Here are some snippets (I only scroll vertically, but you can easily extend it to also work horizontally):
In your Activity or Fragment (where the NestedScrollView
and WebView
are referenced):
webView.webViewClient = object : WebViewClient() {
overridefunshouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if(url.startsWith("scrollto")) {
val offset = url.replace("scrollto://", "");
val offsetInt = MapUtils.getDensityIndependentPixels(offset.toFloat(), requireContext()).toInt()
(webView.parent as NestedScrollView).scrollTo(0, offsetInt)
returntrue
}
returnfalse
}
}
//We need this, because the measured pixels in the WebView don't use density of the screenfungetDensityIndependentPixels(pixels: Float, context: Context): Float {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
pixels,
context.resources.displayMetrics
)
}
Then in your Javascript (or <script>
-Tag in the HTML):
functiongetOffset(el) {
const rect = el.getBoundingClientRect();
return {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset
};
}
functionmakeItScroll(id) {
var element = document.getElementById(id)
var offsetTop = getOffset(element).topwindow.location = "scrollto://"+offsetTop
}
And finally use it inside your HTML like this:
div
you want to scroll to: <div id="here">...</div>
a
to scroll there: <a href="javascript:makeItScroll('here');">...</a>
Post a Comment for "Webview With Anchors Inside Nestedscrollview"