最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Android实现图片拖动效果
时间:2022-06-25 23:26:53 编辑:袖梨 来源:一聚教程网
要求:
1.通过手指移动来拖动图片
2.控制图片不能超出屏幕显示区域
技术点:
1.MotionEvent处理
2.对View进行动态定位(layout)
activity_main.xml:
| 代码如下 | 复制代码 |
xmlns:tools="http://schemas.and***roid.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> android:id="@+id/iv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/test"/> |
|
MainActivity:
| 代码如下 | 复制代码 |
|
publicclassMainActivityextendsActivityimplementsOnTouchListener { privateImageView iv_main; privateRelativeLayout parentView; @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_main = (ImageView) findViewById(R.id.iv_main); parentView = (RelativeLayout) iv_main.getParent(); /* int right = parentView.getRight(); //0 int bottom = parentView.getBottom(); //0 Toast.makeText(this, right+"---"+bottom, 1).show(); */ //设置touch监听 iv_main.setOnTouchListener(this); } privateintlastX; privateintlastY; privateintmaxRight; privateintmaxBottom; @Override publicbooleanonTouch(View v, MotionEvent event) { //得到事件的坐标 inteventX = (int) event.getRawX(); inteventY = (int) event.getRawY(); switch(event.getAction()) { caseMotionEvent.ACTION_DOWN: //得到父视图的right/bottom if(maxRight==0) {//保证只赋一次值 maxRight = parentView.getRight(); maxBottom = parentView.getBottom(); } //第一次记录lastX/lastY lastX =eventX; lastY = eventY; break; caseMotionEvent.ACTION_MOVE: //计算事件的偏移 intdx = eventX-lastX; intdy = eventY-lastY; //根据事件的偏移来移动imageView intleft = iv_main.getLeft()+dx; inttop = iv_main.getTop()+dy; intright = iv_main.getRight()+dx; intbottom = iv_main.getBottom()+dy; //限制left >=0 if(left right += -left; left =0; } //限制top if(top bottom += -top; top =0; } //限制right if(right>maxRight) { left -= right-maxRight; right = maxRight; } //限制bottom if(bottom>maxBottom) { top -= bottom-maxBottom; bottom = maxBottom; } iv_main.layout(left, top, right, bottom); //再次记录lastX/lastY lastX = eventX; lastY = eventY; break; default: break; } returntrue;//所有的motionEvent都交给imageView处理 } } |
|
相关文章
- GitHub Copilot开发者最佳实践:团队协作中5项检查清单 06-11
- 云上智农app如何申报农民专项信贷 06-11
- 京东白拿活动入口 - 2026最新免费领商品攻略 06-11
- Cursor开发者进阶技巧:如何用代码审查功能提升团队效率? 06-11
- Cursor怎么低成本使用?2026年3个免费技巧 06-11
- Cursor开发者报错怎么解决?3种排查方法 06-11