Android控件拖动实例详解
程序员文章站
2024-02-23 10:56:34
android控件拖动
android控件的拖动,主要是通过设置控件的setontouchlistener()方法,重写它的ontouch()方法。然后通过motione...
android控件拖动
android控件的拖动,主要是通过设置控件的setontouchlistener()方法,重写它的ontouch()方法。然后通过motionevent的不同事件,进行判断,主要是在motionevent.action_move中不断重绘控件在画布中的位置,而实现拖动的效果。
public class dragviewactivity extends appcompatactivity { private button btn_drag; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_drag_view); // 获取屏幕的宽高 displaymetrics dm = getresources().getdisplaymetrics(); final int screenwith = dm.widthpixels; final int screenheight = dm.heightpixels; btn_drag = (button) findviewbyid(r.id.btn_drag); btn_drag.setontouchlistener(new view.ontouchlistener() { int lastx; int lasty; boolean isdraging = false; @override public boolean ontouch(view v, motionevent event) { int ee = event.getaction(); switch (ee){ case motionevent.action_down: isdraging = true; lastx = (int) event.getrawx(); lasty = (int) event.getrawy(); break; case motionevent.action_move: if (isdraging){ // x轴方向的位移差 int dx = (int) event.getrawx() - lastx; // y轴方向的位移差 int dy = (int) event.getrawy() - lasty; int l = v.getleft() + dx; int t = v.gettop() + dy; int r = v.getright() + dx; int b = v.getbottom() + dy; // 判断超出屏幕 if (l < 0){ l = 0; r = l + v.getwidth(); } if (t < 0){ t = 0; b = t + v.getheight(); } if (r > screenwith){ r = screenwith; l = r - v.getwidth(); } if (b > screenheight){ b = screenheight; t = b - v.getheight(); } // 重绘view v.layout(l, t, r, b); v.postinvalidate(); lastx = (int) event.getrawx(); lasty = (int) event.getrawy(); } break; case motionevent.action_up: isdraging = false; break; default: break; } return false; } }); }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!