大佬教程收集整理的这篇文章主要介绍了Android实现图片拖动效果,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
要求:
1.通过手指移动来拖动图片
技术点:
1.MotionEvent处理
2.对View进行动态定位(layout)
activity_main.xml:
<RelativeLayout xmlns:android="http://scheR_473_11845@as.android.com/apk/res/android" xmlns:tools="http://scheR_473_11845@as.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/iv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/test"/> </RelativeLayout>
@H_653_1@mainActivity:
public class MainActivity extends Activity implements OnTouchListener { private ImageView iv_main; private RelativeLayout parentView; @Override protected void onCreate(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); } privatE int lastX; privatE int lastY; privatE int maxRight; privatE int maxBottom; @Override public Boolean onTouch(View v,MotionEvent event) { //得到事件的坐标 int eventX = (int) event.getRawX(); int eventY = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //得到父视图的right/bottom if(maxRight==0) {//保证只赋一次值 maxRight = parentView.getright(); maxBottom = parentView.getBottom(); } //第一次记录lastX/lastY lastX =eventX; lastY = eventY; break; case MotionEvent.ACTION_MOVE: //计算事件的偏移 int dx = eventX-lastX; int dy = eventY-lastY; //根据事件的偏移来移动imageView int left = iv_main.getLeft()+dx; int top = iv_main.getTop()+dy; int right = iv_main.getright()+dx; int bottom = iv_main.getBottom()+dy; //限制left >=0 if(left<0) { right += -left; left = 0; } //限制top if(top<0) { bottom += -top; top = 0; } //限制right <=maxRight if(right>maxRight) { left -= right-maxRight; right = maxRight; } //限制bottom <=maxBottom if(bottom>maxBottom) { top -= bottom-maxBottom; bottom = maxBottom; } iv_main.layout(left,top,right,bottom); //再次记录lastX/lastY lastX = eventX; lastY = eventY; break; default: break; } return true;//所有的motionEvent都交给imageView处理 } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程小技巧!
以上是大佬教程为你收集整理的Android实现图片拖动效果全部内容,希望文章能够帮你解决Android实现图片拖动效果所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。