Android实现图片拖动效果
程序员文章站
2023-12-03 07:58:39
要求:
1.通过手指移动来拖动图片
2.控制图片不能超出屏幕显示区域
技术点:
1.motionevent处理
2.对view进行动态定位(layou...
要求:
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处理 } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!