Manohar
Manohar

Reputation: 23414

WebView get maximum scroll width

Hello guys i am creating epub reader and loaded the book in android webview and also made webview to move horizontally refering this but now i want to make webview to move like pages so i want to do this way 1.calculate the total horizontalscroll width and screen width , now divide them to get total pages 2.lock the scroll of webview and when ever user swipes ,set the scrolling of webview to screenwidth*swipeCount

now the problem is when i am trying to get totalHorizontalScrollWidth it is giving screen width i tried these ways but both giving same result

FirstMethod

    ViewTreeObserver vto = webView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            webView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            Log.e("ScrollWidth",""+webView.getMeasuredWidth());
            Toast.makeText(getApplicationContext(), "new Width is"+webView.getMeasuredWidth(), Toast.LENGTH_SHORT).show();
        }
    });

returning 480 screen width

and SecondMethod

public class WebViewWidth extends WebView {
public WebViewWidth(Context context) {
    super(context);
}
public WebViewWidth(Context context, AttributeSet attrs) {
    super(context, attrs);
}


public int getContentWidth()
{
    return this.computeHorizontalScrollRange();
}
public int getContentHeight()
{
    return this.computeVerticalScrollRange();
}
}

and used this webView to get computeHorizontalScrollRange like this

private class MyWebViewClient extends WebViewClient {

private Context mContext;


public MyWebViewClient(Context context) {
    this.mContext = context;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    mProgressDialog.dismiss();

    final WebView myWebView = (WebView) view;



    String varMySheet = "var mySheet = document.styleSheets[0];";

    String addCSSRule = "function addCSSRule(selector, newRule) {"
            + "ruleIndex = mySheet.cssRules.length;"
            + "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"

            + "}";

    String insertRule1 = "addCSSRule('html', 'padding: 0px; height: "
            + (myWebView.getMeasuredHeight() / mContext.getResources().getDisplayMetrics().density)
            + "px; -webkit-column-gap: 0px; -webkit-column-width: "
            + myWebView.getMeasuredWidth() + "px;')";


    myWebView.loadUrl("javascript:" + varMySheet);
     myWebView.loadUrl("javascript:" + addCSSRule);
    myWebView.loadUrl("javascript:" + insertRule1);


    super.onPageFinished(view, url);
 int widthis =  webView.getContentWidth();

    Toast.makeText(getApplicationContext(), "Width is"+widthis, Toast.LENGTH_SHORT).show();
    Log.i("WidthTotoal Scroll", ""+widthis);

 }
 }

Even this gives the result as 480 which is the screen size

i also came across this script but dont know how to get values from this script to android

 String js = ""+
    "var desiredHeight;"+
   " var desiredWidth;"+
   " var bodyID = document.getElementsByTagName('body')[0];"+
   " totalHeight = bodyID.offsetHeight;"+
    "pageCount = Math.floor(totalHeight/desiredHeight) + 1;"+
   " bodyID.style.padding = 10;"+ //(optional) prevents clipped letters around the edges
  "  bodyID.style.width = desiredWidth * pageCount;"+
   " bodyID.style.height = desiredHeight;"+
   " bodyID.style.WebkitColumnCount = pageCount;"; 

some one please help me to get the maximum horizontal scroll width of webview or some alternative to get effect like turning pages.

Upvotes: 2

Views: 1697

Answers (2)

Gautam Chibde
Gautam Chibde

Reputation: 1227

I guess I am pretty late but thanks to this I was able to implement smooth horizontal swipe animation in WebView.

Comming to your initial question where you wanted to get the total width of the html page, in my solution I used WebChromeClients onJsAlert() method in which you can get return values from javascript. I use this method to get number of horizontal pages.

In my MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    wv = (HorizontalWebView) findViewById(R.id.web_view);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            injectJavascript();
        }
    });

    wv.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            int pageCount = Integer.parseInt(message);
            wv.setPageCount(pageCount);
            result.confirm();
            return true;
        }
    });
    wv.loadUrl("file:///android_asset/ch03.html");  
}

private void injectJavascript() {
    String js = "function initialize(){\n" +
            "    var d = document.getElementsByTagName('body')[0];\n" +
            "    var ourH = window.innerHeight;\n" +
            "    var ourW = window.innerWidth;\n" +
            "    var fullH = d.offsetHeight;\n" +
            "    var pageCount = Math.floor(fullH/ourH)+1;\n" +
            "    var currentPage = 0;\n" +
            "    var newW = pageCount*ourW;\n" +
            "    d.style.height = ourH+'px';\n" +
            "    d.style.width = newW+'px';\n" +
            "    d.style.margin = 0;\n" +
            "    d.style.webkitColumnCount = pageCount;\n" +
            "    return pageCount;\n" +
            "}";
    wv.loadUrl("javascript:" + js);
    wv.loadUrl("javascript:alert(initialize())");
}

I use javascript:alert(initialize()) to execute javascript function in which I return number of horizontal pages that were created. which I than pass to Custom WebView.

HorizontalWebView.java

public class HorizontalWebView extends WebView {
    private float x1 = -1;
    private int pageCount = 0;

    public HorizontalWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x1 = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                float x2 = event.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > 100) {
                    // Left to Right swipe action
                    if (x2 > x1) {
                        turnPageLeft();
                        return true;
                    }

                    // Right to left swipe action
                    else {
                        turnPageRight();
                        return true;
                    }

                }
                break;
        }
        return true;
    }

    private int current_x = 0;

    private void turnPageLeft() {
        if (getCurrentPage() > 0) {
            int scrollX = getPrevPagePosition();
            loadAnimation(scrollX);
            current_x = scrollX;
            scrollTo(scrollX, 0);
        }
    }

    private int getPrevPagePosition() {
        int prevPage = getCurrentPage() - 1;
        return (int) Math.ceil(prevPage * this.getMeasuredWidth());
    }

    private void turnPageRight() {
        if (getCurrentPage() < pageCount - 1) {
            int scrollX = getNextPagePosition();
            loadAnimation(scrollX);
            current_x = scrollX;
            scrollTo(scrollX, 0);
        }
    }

    private void loadAnimation(int scrollX) {
        ObjectAnimator anim = ObjectAnimator.ofInt(this, "scrollX",
                current_x, scrollX);
        anim.setDuration(500);
        anim.setInterpolator(new LinearInterpolator());
        anim.start();
    }

    private int getNextPagePosition() {
        int nextPage = getCurrentPage() + 1;
        return (int) Math.ceil(nextPage * this.getMeasuredWidth());
    }

    public int getCurrentPage() {
        return (int) (Math.ceil((double) getScrollX() / this.getMeasuredWidth()));
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
}

You can find full working solution here

Upvotes: 2

Manohar
Manohar

Reputation: 23414

i under stood the problem and the solution was to keep a countdown timer and giving 1 sec delay before calculating the width

here is how i did it

 @Override
public void onPageFinished(final WebView view, String url) {


    final WebView myWebView = (WebView) view;



    String varMySheet = "var mySheet = document.styleSheets[0];";

    String addCSSRule = "function addCSSRule(selector, newRule) {"
            + "ruleIndex = mySheet.cssRules.length;"
            + "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"

            + "}";

    String insertRule1 = "addCSSRule('html', 'padding: 0px; height: "
            + (myWebView.getMeasuredHeight() / mContext.getResources().getDisplayMetrics().density)
            + "px; -webkit-column-gap: 0px; -webkit-column-width: "
            + myWebView.getMeasuredWidth() + "px;')";

    String js = ""+
    "var desiredHeight;"+
   " var desiredWidth;"+
   " var bodyID = document.getElementsByTagName('body')[0];"+
   " totalHeight = bodyID.offsetHeight;"+
    "pageCount = Math.floor(totalHeight/desiredHeight) + 1;"+
   " bodyID.style.padding = 10;"+ //(optional) prevents clipped letters around the edges
  "  bodyID.style.width = desiredWidth * pageCount;"+
   " bodyID.style.height = desiredHeight;"+
   " bodyID.style.WebkitColumnCount = pageCount;"+
    "function getPagesCount() {"+
      "  android.getPagesCount(pageCount);"+
  "  };";





    myWebView.loadUrl("javascript:" + varMySheet);
    myWebView.loadUrl("javascript:" + addCSSRule);
    myWebView.loadUrl("javascript:" + insertRule1);





    view.setVisibility(View.VISIBLE);
    super.onPageFinished(view, url);
  CountDownTimer test=  new CountDownTimer(3000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {


        }

        @Override
        public void onFinish() {

            int widthis =  webView.getContentWidth();

            TotalScrollWidth=widthis;
                    Log.i("WidthTotoal Scroll", ""+widthis);
                    TotalPages= (TotalScrollWidth/ScreenWidth)-1;
                    Toast.makeText(getApplicationContext(), "Total Pages are" +TotalPages, 100).show();
                     progressPages.setMax(TotalPages);
                     progressdialog.dismiss();
        }
    };


    test.start();



}

Upvotes: 1

Related Questions