要求:
1.通过手指移动来拖动图片
2.控制图片不能超出屏幕显示区域
技术点:
1.MotionEvent处理
2.对VIEw进行动态定位(layout)
activity_main.xml:
<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.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>
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实现图片拖动效果所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)