布局的監聽事件重寫方法:
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
獲得布局的監聽事件,注意返回值改為true,否則在執行了DOWN以后不再執行UP和MOVE操作。
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;
}
}
}
