Android中的自定义webview与水平滚动

时间:2017-02-13 06:58:30

标签: javascript android css webview webkit

可以自定义webview水平滚动并使用pagination.so我的页面将以块的形式潜入。怎么做到这一点?任何建议我都遇到了这个问题。

webView.setWebViewClient(new WebViewClient(){

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

                ScreenUtils screen = new ScreenUtils(MainActivity.this);

                int deviceHeight = screen.getRealHeight();

                int deviceWidth = screen.getRealWidth();


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

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

                        + "}";


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


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

        });
    }

我已经尝试了上面的代码,但没有分页,底部还有额外的填充。

1 个答案:

答案 0 :(得分:1)

这就是我以前用来实现分页的方式

您必须使用自定义网页浏览才能获得总滚动宽度

这是我使用的

  public class WebViewWidth extends WebView {


     Context context;
     private boolean bAllowScroll = true;

    public WebViewWidth(Context context) {
        super(context);
        this.context = context;

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


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

并在主要活动WebViewWidth webView中作为全局变量

  webView = (WebViewWidth) findViewById(R.id.webView);

当您设置webview客户端

    @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;')";

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


        view.setVisibility(View.VISIBLE);
        super.onPageFinished(view, url);

         //giving delay of 2 sec ,else Totalscrollwidth is giving 0
        CountDownTimer test = new CountDownTimer(3000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) { }

            @Override
            public void onFinish() {

                int widthis = webView.getContentWidth();

                TotalScrollWidth = widthis;

                    TotalPages = (TotalScrollWidth / ScreenWidth) - 1;

                progressdialog.dismiss();

            }
        };
        test.start();
    }

计算webview的屏幕宽度和总滚动宽度

现在totalpages = Totalscrollwidth / screenwidth -1

计算屏幕宽度

 Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;

    ScreenWidth = width;

现在甚至为webview实现自定义滑动,当用户向右滑动时,您可以按屏幕宽度距离滚动webview

像这样的事情

 webView.setOnTouchListener(new OnSwipeTouchListener(this) {
        @Override
        public void onSwipeLeft() {
            // Whatever
            loadnextpage();
        }

        @Override
        public void onSwipeRight() {

            loadpreviouspage();

        } }

  @Override
        public void newTouch() {
         // Do what ever needed for single tap action
        }


    });

  public void loadnextpage() {


    if (TotalPages > PresentPage) {
        PresentPage++;
        webView.scrollTo(PresentPage * ScreenWidth, 0);

    } else {

            Toast.makeText(getApplicationContext(), "The End", Toast.LENGTH_SHORT).show();

    }

我的滑动触摸列表器

 public class OnSwipeTouchListener implements OnTouchListener  {

private final GestureDetector gestureDetector;
private static final int MAX_CLICK_DURATION = 1000;
private static final int MAX_CLICK_DISTANCE = 15;
 static Context mcontext;
private long pressStartTime;
private float pressedX;
private float pressedY;
private boolean stayedWithinClickDistance;
View inflationView;




public  int getLocationx() {
    return Locationx;
}

public void setLocationx(int locationx) {
    Locationx = locationx;
}

public int Locationx;

public int getLocationy() {
    return Locationy;
}

public void setLocationy(int locationy) {
    Locationy = locationy;
}

public int Locationy;

@SuppressWarnings("static-access")
public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
    this.mcontext=context;

}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}
public void newTouch(){

 }

public boolean onTouch(View v, MotionEvent event) {


      this.inflationView=v;
        gestureDetector.onTouchEvent(event);


     if(event.getAction()== MotionEvent.ACTION_MOVE)
     {
          if (stayedWithinClickDistance && distance(pressedX, pressedY, event.getX(), event.getY()) > MAX_CLICK_DISTANCE) {
              stayedWithinClickDistance = false;
          }
         return true;
     }

     else if (event.getAction()== MotionEvent.ACTION_DOWN) {
         pressStartTime = System.currentTimeMillis();                
         pressedX = event.getX();
         pressedY = event.getY();
         stayedWithinClickDistance = true;

         return v.onTouchEvent(event);
     }
     else if(event.getAction()== MotionEvent.ACTION_UP) {

         long pressDuration = System.currentTimeMillis() - pressStartTime;
         if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
            newTouch();
         }
         setLocationx((int)event.getX());
         setLocationy((int)event.getY());
         return v.onTouchEvent(event);
     }
     else{
         return v.onTouchEvent(event);
     }

}
private static float distance(float x1, float y1, float x2, float y2) {
    float dx = x1 - x2;
    float dy = y1 - y2;
    float distanceInPx = (float) Math.sqrt(dx * dx + dy * dy);
    return pxToDp(distanceInPx);
}

private static float pxToDp(float px) {
    return px / mcontext.getResources().getDisplayMetrics().density;
}






 private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_DISTANCE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float distanceX = e2.getX() - e1.getX();
            float distanceY = e2.getY() - e1.getY();
            if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceX > 0)
                    onSwipeRight();
                else
                    onSwipeLeft();
                return true;
            }
            return false;
        }



    }

}