Android之監聽View的兩個指頭是放大和縮小

lvxiangan發表於2018-12-09

我們有時需要對view進行手勢監聽,通過兩個手指開始距離和結束距離,來判斷放大縮小,下面是實現程式碼,所有View通用。

private double nLenStart = 0;//監聽 WebView所用手勢


@Override
            public boolean onTouch(View v, MotionEvent event) {
                int nCnt = event.getPointerCount();
                int n = event.getAction();
                if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN && 2 == nCnt)//<span style="color:#ff0000;">2表示兩個手指</span>
                {
                    for (int i = 0; i < nCnt; i++) {
                        float x = event.getX(i);
                        float y = event.getY(i);
                        Point pt = new Point((int) x, (int) y);
                    }
                    int xlen = Math.abs((int) event.getX(0) - (int) event.getX(1));
                    int ylen = Math.abs((int) event.getY(0) - (int) event.getY(1));
                    nLenStart = Math.sqrt((double) xlen * xlen + (double) ylen * ylen);
                } else if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP && 2 == nCnt) {
                    for (int i = 0; i < nCnt; i++) {
                        float x = event.getX(i);
                        float y = event.getY(i);
                        Point pt = new Point((int) x, (int) y);
                    }
                    int xlen = Math.abs((int) event.getX(0) - (int) event.getX(1));
                    int ylen = Math.abs((int) event.getY(0) - (int) event.getY(1));

                    double nLenEnd = Math.sqrt((double) xlen * xlen + (double) ylen * ylen);

                    if (nLenEnd > nLenStart)//通過兩個手指開始距離和結束距離,來判斷放大縮小
                    {
                        Toast.makeText(getApplicationContext(), "放大", Toast.LENGTH_SHORT).show();
                        tv_web_danGe.getSettings().setTextSize(WebSettings.TextSize.LARGER);
                        tv_web_danGe.reload();
                        tv_web_danGe.loadDataWithBaseURL(null, getHtmlData(content),"text/html","UTF-8",null);//顯示WebView
                    } else {
                        Toast.makeText(getApplicationContext(), "縮小", Toast.LENGTH_SHORT).show();
                        tv_web_danGe.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
                        tv_web_danGe.reload();
                        tv_web_danGe.loadDataWithBaseURL(null, getHtmlData(content),"text/html","UTF-8",null);//顯示WebView
                    }
                }
                return false;
            }

 

相關文章