Android 自定义可拖拽View界面渲染刷新后不会自动回到起始位置
程序员文章站
2024-02-11 20:23:10
以自定义imageview为例:
/**
* 可拖拽imageview
* created by admin on 2017/2/21.
*/
pu...
以自定义imageview为例:
/** * 可拖拽imageview * created by admin on 2017/2/21. */ public class floatingimageview extends imageview{ public floatingimageview(context context) { super(context); } public floatingimageview(context context, attributeset attrs) { super(context, attrs); } public floatingimageview(context context, attributeset attrs, int defstyleattr) { super(context, attrs, defstyleattr); } @targetapi(build.version_codes.lollipop) public floatingimageview(context context, attributeset attrs, int defstyleattr, int defstyleres) { super(context, attrs, defstyleattr, defstyleres); } int startx; int starty; int left; int top; int[] temp = new int[]{ 0, 0 }; @override public boolean ontouchevent(motionevent event) { boolean ismove = false; int x = (int) event.getrawx(); int y = (int) event.getrawy(); switch (event.getaction()){ case motionevent.action_down: // touch down so check if the startx = x; starty = y; temp[0] = (int) event.getx(); temp[1] = y - gettop(); break; case motionevent.action_move: // touch drag with the ball left = x - temp[0]; top = y - temp[1]; if(left < 0){//控制左边界不超出 left = 0; } layout(left, top, left + getwidth(),top + getheight());//*拖拽 break; case motionevent.action_up: if (math.abs(x - startx) > 2 || math.abs(y - starty) > 2){//判断是否移动,再一定范围内不算是移动,解决触发事件冲突 //将最后拖拽的位置定下来,否则页面刷新渲染后按钮会自动回到初始位置 //注意父容器 relativelayout.layoutparams lp = (relativelayout.layoutparams) getlayoutparams(); lp.setmargins(left, top,0,0); setlayoutparams(lp); //确定是拖拽 ismove = true; } break; } return ismove ? true : super.ontouchevent(event); } }
以上所述是小编给大家介绍的android 自定义可拖拽view界面渲染刷新后不会自动回到起始位置,希望对大家有所帮助
上一篇: 猪肘子的做法大全有哪些!