码迷,mamicode.com
首页 > 移动开发 > 详细

Android可移动控件

时间:2015-09-18 15:27:20      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

可移动控件:

效果图:

技术分享

获取屏幕的宽高:

1         DisplayMetrics dm = getResources().getDisplayMetrics();
2         screenWidth = dm.widthPixels;
3         screenHeight = dm.heightPixels - 50;
4         ImageView imageView = (ImageView)findViewById(R.id.spirit_img);
5         imageView.setOnTouchListener(this);

 

onTouch设定: 

 1     @Override
 2     public boolean onTouch(View v, MotionEvent event) {
 3         int action = event.getAction();
 4         switch (action){
 5             case MotionEvent.ACTION_DOWN:
 6                 lastX = (int) event.getRawX();
 7                 lastY = (int) event.getRawY();
 8                 break;
 9             case MotionEvent.ACTION_MOVE:
10                 int dx =(int)event.getRawX() - lastX;
11                 int dy =(int)event.getRawY() - lastY;
12                 int left = v.getLeft() + dx;
13                 int top = v.getTop() + dy;
14                 int right = v.getRight() + dx;
15                 int bottom = v.getBottom() + dy;
16                 if(left < 0){
17                     left = 0;
18                     right = left + v.getWidth();
19                 }
20                 if(right > screenWidth){
21                     right = screenWidth;
22                     left = right - v.getWidth();
23                 }
24                 if(top < 0){
25                     top = 0;
26                     bottom = top + v.getHeight();
27                 }
28                 if(bottom > screenHeight){
29                     bottom = screenHeight;
30                     top = bottom - v.getHeight();
31                 }
32                 v.layout(left, top, right, bottom);
33                 lastX = (int) event.getRawX();
34                 lastY = (int) event.getRawY();
35                 break;
36         }
37         return false;
38     }

 

layout的办法有一个问题,viewgroup里面的其他东西刷新,imageview就会归位。

 

Android可移动控件

标签:

原文地址:http://www.cnblogs.com/lfk-dsk/p/4819052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!