Getting a maximum scroll value of a webview

2019-07-15 10:52发布

问题:

I know in Scrollview you can access scrollView.getMaxScrollAmount however I don't seem to understand how to call it on webview. I tried cheating to get the information about it. Here is what I tried.

What the method was suppose to do is that it continually scroll in a specific amount and checks if the value isn't increased in that amount it gets that amount and returns it with the max value. However it doesn't work.

public String scrollToMAX(){
        webView1.scrollTo(0, 0);
        Boolean istrue = true;
        String getIntData = "";
        int i = 0;
        while(istrue){
            int checker = webView1.getScrollY();
            if(i != checker){
                i = checker;
                getIntData = Integer.toString(i);
                istrue = false;
            }
            i=i+5000;
            webView1.scrollTo(0, i);
        }
        webView1.scrollTo(0, 0);
        return getIntData;
        //Put a return string here
    } 

回答1:

here you go: this is working perfectly for me (it scrolls to the end)

the trick is in using the function getContentHeight of WebView

package sherif.android.activity;

import sherif.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebClientTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        WebView webView = new WebView(this);
        String UserAgent = "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; 
        //webView.getSettings().setUserAgentString(UserAgent); 
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.google.com/search?gcx=w&sourceid=chrome&ie=UTF-8&q=arsenal");
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.v("here","here");
                view.scrollBy(0, view.getContentHeight());
            }
        });
        setContentView(webView);
    }
}


回答2:

A bit late, but if anyone needs the answer, webview has a protected method - computeVerticalScrollRange() - if you want to know the max scroll range you can override the WebView and return computeVerticalScrollRange() - getHeight()