你好,游客 登录 注册 搜索
背景:
阅读新闻

Android控件拖动的实现【源码】

[日期:2012-06-18] 来源:Linux社区  作者:chengxibeauty [字体:大 中 小]

高度减去50是减去状态栏和标题栏的高度。

  1. case MotionEvent.ACTION_DOWN:  
  2.             lastX = (int) event.getRawX();  
  3.             lastY = (int) event.getRawY();  
  4.             break;  

然后获取控件一开始的位置,然后在ACTION_MOVIE中:

  1. int dx =(int)event.getRawX() - lastX;  
  2.             int dy =(int)event.getRawY() - lastY;  
  3.           
  4.             int left = v.getLeft() + dx;  
  5.             int top = v.getTop() + dy;  
  6.             int right = v.getRight() + dx;  
  7.             int bottom = v.getBottom() + dy;                      
  8.             if(left < 0){  
  9.                 left = 0;  
  10.                 right = left + v.getWidth();  
  11.             }                     
  12.             if(right > screenWidth){  
  13.                 right = screenWidth;  
  14.                 left = right - v.getWidth();  
  15.             }                     
  16.             if(top < 0){  
  17.                 top = 0;  
  18.                 bottom = top + v.getHeight();  
  19.             }                     
  20.             if(bottom > screenHeight){  
  21.                 bottom = screenHeight;  
  22.                 top = bottom - v.getHeight();  
  23.             }                     
  24.             v.layout(left, top, right, bottom);  
  25.             Log.i("@@@@@@", "position??" + left +", " + top + ", " + right + ", " + bottom);     
  26.             lastX = (int) event.getRawX();  
  27.             lastY = (int) event.getRawY();    

getLeft()方法得到的是控件坐标距离父控件原点(左上角,坐标(0,0))的x轴距离,getReght()是控件右边距离父控件原点的x轴距离,同理,getTop和getButtom是距离的y轴距离。

  1. if(left < 0){  
  2.                 left = 0;  
  3.                 right = left + v.getWidth();  
  4.             }                     
  5.             if(right > screenWidth){  
  6.                 right = screenWidth;  
  7.                 left = right - v.getWidth();  
  8.             }                     
  9.             if(top < 0){  
  10.                 top = 0;  
  11.                 bottom = top + v.getHeight();  
  12.             }                     
  13.             if(bottom > screenHeight){  
  14.                 bottom = screenHeight;  
  15.                 top = bottom - v.getHeight();  
  16.             }     
linux
相关资讯       Android开发入门 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* d 发表于 2012/8/16 11:18:19
dddd