package com.blog.demo11; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import androidx.annotation.Nullable; import com.blog.BaseActivity; import com.blog.R; import static android.view.MotionEvent.INVALID_POINTER_ID; /** * 可拖拽效果类。 */ public class ViewDragActivity extends BaseActivity { private ImageView backgroundImage; private ImageView image1; private ImageView image2; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); backgroundImage = findViewById(R.id.background_image); image1 = findViewById(R.id.image1); image2 = findViewById(R.id.image2); // Set touch listeners for each image image1.setOnTouchListener(new MultiTouchListener()); image2.setOnTouchListener(new MultiTouchListener()); } private class MultiTouchListener implements View.OnTouchListener { private float lastTouchX, lastTouchY; private int activePointerId = INVALID_POINTER_ID; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: { final int pointerIndex = event.getActionIndex(); final float x = event.getX(pointerIndex); final float y = event.getY(pointerIndex); lastTouchX = x; lastTouchY = y; activePointerId = event.getPointerId(pointerIndex); break; } case MotionEvent.ACTION_MOVE: { final int pointerIndex = event.findPointerIndex(activePointerId); final float x = event.getX(pointerIndex); final float y = event.getY(pointerIndex); final float dx = x - lastTouchX; final float dy = y - lastTouchY; v.setX(v.getX() + dx); v.setY(v.getY() + dy); lastTouchX = x; lastTouchY = y; break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { activePointerId = INVALID_POINTER_ID; break; } case MotionEvent.ACTION_POINTER_UP: { final int pointerIndex = event.getActionIndex(); final int pointerId = event.getPointerId(pointerIndex); if (pointerId == activePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; lastTouchX = event.getX(newPointerIndex); lastTouchY = event.getY(newPointerIndex); activePointerId = event.getPointerId(newPointerIndex); } break; } } return true; } } }
时间: 2024-02-10 12:08:55 浏览: 112
Android Studio 升级到3.0 提示 java.lang.NoClassDefFoundError的解决方法
这是一段 Android 应用程序代码,实现了一个可拖拽效果类 ViewDragActivity。在该类中,通过监听 onTouch 事件来实现多指触摸拖拽图片的效果,其中 MultiTouchListener 类实现了 View.OnTouchListener 接口,重写了 onTouch 方法,通过获取 MotionEvent 的不同事件来实现图片的移动。具体实现过程可以参考代码中的注释。
阅读全文