Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

android - WebView scrollTo is not working

I'm trying to use scrollTo method of webview. This my layout file for the webview.

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
  xmlns:android="http://schemas.android.com/apk/res/android"  
  android:orientation="vertical"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent"   
>  
<WebView  
   android:id="@+id/webMap"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
 />  
</LinearLayout> 

What I'm trying to do is showing a html file (which has only a map image) and scrolling to certain area on image with :

mapWebView.loadUrl("file:///android_asset/maps/map.html");
mapWebView.scrollTo(300, 300);

But when the webview is loaded it always shows the (0, 0) of the image.

What is the problem with scrollTo() here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect that mapWebView.loadUrl("file:///android_asset/maps/map.html"); is asynchronous, so mapWebView.scrollTo(300, 300); executes before the webview has finished loading. Once the page loads it will have lost the scroll setting you applied and will be reset to the top.

You need to listen in for the the page loading and then scroll it:

mapWebView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
            mapWebView.scrollTo(300, 300);
        }

    }
    );

Hope this helps

EDIT: Turns out this is unreliable, use this instead:

mapWebView.setPictureListener(new PictureListener() {

        @Override
        public void onNewPicture(WebView view, Picture picture) {
             mapWebView.scrollTo(300, 300);

        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...