Android可移动控件

可移动控件:

效果图:

获取屏幕的宽高:

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就会归位。

 

posted @ 2015-09-18 14:05  刘丰恺  阅读(1176)  评论(0编辑  收藏  举报