Reputation: 159
Is there any way to get Android WebView content width after the webpage loaded with vertical scroll using java?
Upvotes: 5
Views: 9578
Reputation: 9153
You need the width and height of the WebView CONTENTS, after you loaded your HTML. YES you do, but there is no getContentWidth method (only a view port value), AND the getContentHeight() is inaccurate !
Answer: sub-class WebView:
/*
Jon Goodwin
*/
package com.example.html2pdf;//your package
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
class CustomWebView extends WebView
{
public int rawContentWidth = 0; //unneeded
public int rawContentHeight = 0; //unneeded
Context mContext = null; //unneeded
public CustomWebView(Context context) //unused constructor
{
super(context);
mContext = this.getContext();
}
public CustomWebView(Context context, AttributeSet attrs) //inflate constructor
{
super(context,attrs);
mContext = context;
}
public int getContentWidth()
{
int ret = super.computeHorizontalScrollRange();//working after load of page
rawContentWidth = ret;
return ret;
}
public int getContentHeight()
{
int ret = super.computeVerticalScrollRange(); //working after load of page
rawContentHeight = ret;
return ret;
}
//=========
}//class
//=========
Upvotes: 4
Reputation: 301
In case you have the option to extend the used WebView you can also try the output of the protected Method computeHorizontalScrollRange().
Update: I forgot to mention that this only works properly if the content is bigger than the webview.
class YourCustomWebView extends WebView {
public YourCustomWebView(Context context) {
super(context);
}
public int getContentWidth()
{
return this.computeHorizontalScrollRange();
}
}
public void onPageFinished(WebView page, String url) {
Log.v(LOG_TAG,"ContentWidth: " + ((YourCustomWebView) page).getContentWidth());
}
Upvotes: 8
Reputation: 3579
Please check, http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/
There is method webview.getContentHeight();
for getting the content height. There is no method to get the content width. You can do that using javascript, and getting it from javascript using JavaScriptInterface. Since you are loading from assets folder, you can easily add the javascript function and make a JavascriptInterface.
Upvotes: 0