Rumah >Java >javaTutorial >安卓实现拖动功能~整理~亲测可用
开发安卓应用,你需要先安装 eclipse 和 jdk 和 sdk ,然后创建安卓手机模拟器。这里就不多说了。
安卓的拖动功能在很多场景中都会出现,那么如何实现这一功能,经本人修改调试通过。
代码如下:
先在试图界面上创建imageView1与imageView2两个实例,再将下面代码贴入java类文件中
private int screenWidth; private int screenHeight; private ImageView img1; private ImageView img2; img1 = (ImageView) findViewById(R.id.imageView1); img2 = (ImageView) findViewById(R.id.imageView2); DisplayMetrics dm = getResources().getDisplayMetrics(); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels - 50; img1.setOnTouchListener(movingEventListener); img2.setOnTouchListener(movingEventListener); private OnTouchListener movingEventListener = new OnTouchListener() { int lastX, lastY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE: int dx = (int) event.getRawX() - lastX; int dy = (int) event.getRawY() - lastY; int left = v.getLeft() + dx; int top = v.getTop() + dy; int right = v.getRight() + dx; int bottom = v.getBottom() + dy; // ÉèÖò»Äܳö½ç if (left < 0) { left = 0; right = left + v.getWidth(); } if (right > screenWidth) { right = screenWidth; left = right - v.getWidth(); } if (top < 0) { top = 0; bottom = top + v.getHeight(); } if (bottom > screenHeight) { bottom = screenHeight; top = bottom - v.getHeight(); } v.layout(left, top, right, bottom); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_UP: break; } return true; } };
是不是已经成功了,欢迎来php中文网学习编程
文章地址:http://www.php.cn/java-article-375823.html
______________ PHP中文网 _______________
Atas ialah kandungan terperinci 安卓实现拖动功能~整理~亲测可用. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!