佈局的監聽事件重寫方法:java
layout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } });
得到佈局的監聽事件,注意返回值改成true,不然在執行了DOWN之後再也不執行UP和MOVE操做。ide
public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE break; } return true; }
得到在屏幕上點擊數量(即手指數量)的函數,每個手機能夠得到的最大數量不等函數
event.getPointerCount()
能夠經過move對圖片的大小進行操做佈局
case MotionEvent.ACTION_MOVE: if (event.getPointerCount() >= 2) { float offsetX = event.getX(0) - event.getX(1);//監聽手機的PointerCount數量大於2時,得到兩個點的座標 float offsetY = event.getY(0) - event.getY(1); currentdistance = (float) Math.sqrt(offsetX * offsetX + offsetY * offsetY); if (lastdistance < 0) { lastdistance = currentdistance; } else { if (currentdistance - lastdistance > 5) {//像素改變大於5是爲了容錯的存在 RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) img.getLayoutParams(); layoutParams.width = (int) (img.getWidth() * 1.1); layoutParams.height = (int) (img.getHeight() * 1.1); img.setLayoutParams(layoutParams); lastdistance = currentdistance; } else if (lastdistance - currentdistance > 5) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) img.getLayoutParams(); layoutParams.width = (int) (img.getWidth() * 0.9); layoutParams.height = (int) (img.getHeight() * 0.9); img.setLayoutParams(layoutParams); lastdistance = currentdistance; } } }