Skip to content Skip to sidebar Skip to footer

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 pa

Solution 1:

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 WebChromeClientsonJsAlert() method in which you can get return values from javascript. I use this method to get number of horizontal pages.

In my MainActivity.java

@OverrideprotectedvoidonCreate(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(newWebViewClient() {

        publicvoidonPageFinished(WebView view, String url) {
            injectJavascript();
        }
    });

    wv.setWebChromeClient(newWebChromeClient() {
        @OverridepublicbooleanonJsAlert(WebView view, String url, String message, JsResult result) {
            int pageCount = Integer.parseInt(message);
            wv.setPageCount(pageCount);
            result.confirm();
            returntrue;
        }
    });
    wv.loadUrl("file:///android_asset/ch03.html");  
}

privatevoidinjectJavascript() {
    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

publicclassHorizontalWebViewextendsWebView {
    privatefloatx1= -1;
    privateintpageCount=0;

    publicHorizontalWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @OverridepublicbooleanonTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x1 = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                floatx2= event.getX();
                floatdeltaX= x2 - x1;
                if (Math.abs(deltaX) > 100) {
                    // Left to Right swipe actionif (x2 > x1) {
                        turnPageLeft();
                        returntrue;
                    }

                    // Right to left swipe actionelse {
                        turnPageRight();
                        returntrue;
                    }

                }
                break;
        }
        returntrue;
    }

    privateintcurrent_x=0;

    privatevoidturnPageLeft() {
        if (getCurrentPage() > 0) {
            intscrollX= getPrevPagePosition();
            loadAnimation(scrollX);
            current_x = scrollX;
            scrollTo(scrollX, 0);
        }
    }

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

    privatevoidturnPageRight() {
        if (getCurrentPage() < pageCount - 1) {
            intscrollX= getNextPagePosition();
            loadAnimation(scrollX);
            current_x = scrollX;
            scrollTo(scrollX, 0);
        }
    }

    privatevoidloadAnimation(int scrollX) {
        ObjectAnimatoranim= ObjectAnimator.ofInt(this, "scrollX",
                current_x, scrollX);
        anim.setDuration(500);
        anim.setInterpolator(newLinearInterpolator());
        anim.start();
    }

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

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

    publicvoidsetPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
}

You can find full working solution here

Solution 2:

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

@OverridepublicvoidonPageFinished(final WebView view, String url) {


    finalWebViewmyWebView= (WebView) view;



    StringvarMySheet="var mySheet = document.styleSheets[0];";

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

            + "}";

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

    Stringjs=""+
    "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=  newCountDownTimer(3000,1000) {

        @OverridepublicvoidonTick(long millisUntilFinished) {


        }

        @OverridepublicvoidonFinish() {

            intwidthis=  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();



}

Post a Comment for "Webview Get Maximum Scroll Width"